Coverage Report

Created: 2024-04-18 01:10

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90.5
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
442
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
443
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
444
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
445
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
446
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
447
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
448
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
449
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
450
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
451
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
452
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
453
                           - old: BeginChild("Name", size, true)
454
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
455
                           - old: BeginChild("Name", size, false)
456
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
457
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
458
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
459
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
460
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
461
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
462
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
463
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
464
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
465
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
466
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
467
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
468
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
469
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
470
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
471
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
472
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
473
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
474
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
475
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
476
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
477
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
478
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
479
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
480
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
481
                           - ListBoxFooter()  -> use EndListBox()
482
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
483
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
484
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
485
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
486
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
487
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
488
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
489
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
490
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
491
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
492
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
493
                         it has been frequently requested by people to use our own. We had an opt-in define which was
494
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
495
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
496
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
497
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
498
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
499
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
500
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
501
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
502
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
503
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
504
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
505
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
506
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
507
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
508
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
509
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
510
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
511
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
512
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
513
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
514
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
515
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
516
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
517
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
518
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
519
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
520
                         - previously this would make the window content size ~200x200:
521
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
522
                         - instead, please submit an item:
523
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
524
                         - alternative:
525
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
526
                         - content size is now only extended when submitting an item!
527
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
528
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
529
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
530
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
531
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
532
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
533
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
534
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
535
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
536
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
537
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
538
                        - Official backends from 1.87+                  -> no issue.
539
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
540
                        - Custom backends not writing to io.NavInputs[] -> no issue.
541
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
542
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
543
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
544
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
545
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
546
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
547
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
548
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
549
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
550
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
551
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
552
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
553
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
554
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
555
                       read https://github.com/ocornut/imgui/issues/4921 for details.
556
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
557
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
558
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
559
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
560
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
561
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
562
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
563
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
564
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
565
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
566
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
567
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
568
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
569
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
570
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
571
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
572
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
573
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
574
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
575
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
576
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
577
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
578
                        - if you are using official backends from the source tree: you have nothing to do.
579
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
580
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
581
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
582
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
583
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
584
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
585
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
586
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
587
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
588
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
589
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
590
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
591
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
592
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
593
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
594
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
595
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
596
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
597
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
598
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
599
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
600
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
601
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
602
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
603
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
604
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
605
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
606
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
607
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
608
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
609
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
610
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
611
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
612
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
613
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
614
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
615
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
616
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
617
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
618
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
619
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
620
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
621
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
622
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
623
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
624
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
625
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
626
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
627
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
628
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
629
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
630
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
631
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
632
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
633
                       - if you omitted the 'power' parameter (likely!), you are not affected.
634
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
635
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
636
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
637
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
638
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
639
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
640
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
641
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
642
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
643
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
644
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
645
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
646
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
647
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
648
                       - ShowTestWindow()                    -> use ShowDemoWindow()
649
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
650
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
651
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
652
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
653
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
654
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
655
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
656
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
657
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
658
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
659
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
660
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
661
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
662
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
663
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
664
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
665
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
666
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
667
                       - ImFont::Glyph                       -> use ImFontGlyph
668
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
669
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
670
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
671
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
672
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
673
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
674
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
675
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
676
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
677
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
678
                       Please reach out if you are affected.
679
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
680
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
681
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
682
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
683
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
684
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
685
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
686
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
687
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
688
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
689
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
690
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
691
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
692
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
693
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
694
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
695
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
696
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
697
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
698
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
699
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
700
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
701
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
702
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
703
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
704
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
705
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
706
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
707
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
708
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
709
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
710
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
711
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
712
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
713
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
714
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
715
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
716
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
717
                       consistent with other functions. Kept redirection functions (will obsolete).
718
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
719
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
720
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
721
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
722
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
723
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
724
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
725
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
726
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
727
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
728
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
729
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
730
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
731
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
732
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
733
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
734
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
735
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
736
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
737
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
738
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
739
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
740
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
741
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
742
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
743
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
744
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
745
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
746
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
747
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
748
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
749
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
750
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
751
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
752
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
753
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
754
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
755
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
756
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
757
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
758
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
759
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
760
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
761
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
762
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
763
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
764
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
765
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
766
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
767
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
768
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
769
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
770
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
771
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
772
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
773
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
774
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
775
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
776
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
777
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
778
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
779
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
780
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
781
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
782
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
783
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
784
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
785
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
786
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
787
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
788
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
789
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
790
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
791
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
792
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
793
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
794
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
795
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
796
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
797
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
798
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
799
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
800
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
801
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
802
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
803
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
804
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
805
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
806
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
807
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
808
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
809
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
810
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
811
                     - the signature of the io.RenderDrawListsFn handler has changed!
812
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
813
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
814
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
815
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
816
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
817
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
818
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
819
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
820
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
821
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
822
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
823
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
824
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
825
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
826
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
827
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
828
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
829
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
830
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
831
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
832
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
833
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
834
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
835
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
836
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
837
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
838
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
839
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
840
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
841
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
842
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
843
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
844
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
845
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
846
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
847
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
848
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
849
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
850
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
851
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
852
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
853
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
854
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
855
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
856
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
857
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
858
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
859
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
860
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
861
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
862
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
863
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
864
865
866
 FREQUENTLY ASKED QUESTIONS (FAQ)
867
 ================================
868
869
 Read all answers online:
870
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
871
 Read all answers locally (with a text editor or ideally a Markdown viewer):
872
   docs/FAQ.md
873
 Some answers are copied down here to facilitate searching in code.
874
875
 Q&A: Basics
876
 ===========
877
878
 Q: Where is the documentation?
879
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
880
    - Run the examples/ applications and explore them.
881
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
882
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
883
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
884
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
885
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
886
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
887
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
888
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
889
    - Your programming IDE is your friend, find the type or function declaration to find comments
890
      associated with it.
891
892
 Q: What is this library called?
893
 Q: Which version should I get?
894
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
895
 >> See https://www.dearimgui.com/faq for details.
896
897
 Q&A: Integration
898
 ================
899
900
 Q: How to get started?
901
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
902
903
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
904
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
905
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
906
907
 Q. How can I enable keyboard or gamepad controls?
908
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
909
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
910
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
911
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
912
 >> See https://www.dearimgui.com/faq
913
914
 Q&A: Usage
915
 ----------
916
917
 Q: About the ID Stack system..
918
   - Why is my widget not reacting when I click on it?
919
   - How can I have widgets with an empty label?
920
   - How can I have multiple widgets with the same label?
921
   - How can I have multiple windows with the same label?
922
 Q: How can I display an image? What is ImTextureID, how does it work?
923
 Q: How can I use my own math types instead of ImVec2?
924
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
925
 Q: How can I display custom shapes? (using low-level ImDrawList API)
926
 >> See https://www.dearimgui.com/faq
927
928
 Q&A: Fonts, Text
929
 ================
930
931
 Q: How should I handle DPI in my application?
932
 Q: How can I load a different font than the default?
933
 Q: How can I easily use icons in my application?
934
 Q: How can I load multiple fonts?
935
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
936
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
937
938
 Q&A: Concerns
939
 =============
940
941
 Q: Who uses Dear ImGui?
942
 Q: Can you create elaborate/serious tools with Dear ImGui?
943
 Q: Can you reskin the look of Dear ImGui?
944
 Q: Why using C++ (as opposed to C)?
945
 >> See https://www.dearimgui.com/faq
946
947
 Q&A: Community
948
 ==============
949
950
 Q: How can I help?
951
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
952
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
953
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
954
      >>> See https://github.com/ocornut/imgui/wiki/Funding
955
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
956
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
957
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
958
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
959
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
960
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
961
962
*/
963
964
//-------------------------------------------------------------------------
965
// [SECTION] INCLUDES
966
//-------------------------------------------------------------------------
967
968
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
969
#define _CRT_SECURE_NO_WARNINGS
970
#endif
971
972
#ifndef IMGUI_DEFINE_MATH_OPERATORS
973
#define IMGUI_DEFINE_MATH_OPERATORS
974
#endif
975
976
#include "imgui.h"
977
#ifndef IMGUI_DISABLE
978
#include "imgui_internal.h"
979
980
// System includes
981
#include <stdio.h>      // vsnprintf, sscanf, printf
982
#include <stdint.h>     // intptr_t
983
984
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
985
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
986
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
987
#endif
988
989
// [Windows] OS specific includes (optional)
990
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
991
#define IMGUI_DISABLE_WIN32_FUNCTIONS
992
#endif
993
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
994
#ifndef WIN32_LEAN_AND_MEAN
995
#define WIN32_LEAN_AND_MEAN
996
#endif
997
#ifndef NOMINMAX
998
#define NOMINMAX
999
#endif
1000
#ifndef __MINGW32__
1001
#include <Windows.h>        // _wfopen, OpenClipboard
1002
#else
1003
#include <windows.h>
1004
#endif
1005
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
1006
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1007
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1008
#endif
1009
#endif
1010
1011
// [Apple] OS specific includes
1012
#if defined(__APPLE__)
1013
#include <TargetConditionals.h>
1014
#endif
1015
1016
// Visual Studio warnings
1017
#ifdef _MSC_VER
1018
#pragma warning (disable: 4127)             // condition expression is constant
1019
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1020
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1021
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1022
#endif
1023
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1024
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1025
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1026
#endif
1027
1028
// Clang/GCC warnings with -Weverything
1029
#if defined(__clang__)
1030
#if __has_warning("-Wunknown-warning-option")
1031
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1032
#endif
1033
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1034
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1035
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1036
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1037
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1038
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1039
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1040
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1041
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1042
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1043
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1044
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1045
#elif defined(__GNUC__)
1046
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1047
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1048
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1049
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1050
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1051
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1052
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1053
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1054
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1055
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1056
#endif
1057
1058
// Debug options
1059
44.8k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1060
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1061
1062
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1063
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1064
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1065
1066
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1067
1068
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1069
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1070
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1071
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1072
1073
// Tooltip offset
1074
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1075
1076
// Docking
1077
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1078
1079
//-------------------------------------------------------------------------
1080
// [SECTION] FORWARD DECLARATIONS
1081
//-------------------------------------------------------------------------
1082
1083
static void             SetCurrentWindow(ImGuiWindow* window);
1084
static void             FindHoveredWindow();
1085
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1086
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1087
1088
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1089
1090
// Settings
1091
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1092
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1093
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1094
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1095
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1096
1097
// Platform Dependents default implementation for IO functions
1098
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1099
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1100
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1101
1102
namespace ImGui
1103
{
1104
// Navigation
1105
static void             NavUpdate();
1106
static void             NavUpdateWindowing();
1107
static void             NavUpdateWindowingOverlay();
1108
static void             NavUpdateCancelRequest();
1109
static void             NavUpdateCreateMoveRequest();
1110
static void             NavUpdateCreateTabbingRequest();
1111
static float            NavUpdatePageUpPageDown();
1112
static inline void      NavUpdateAnyRequestFlag();
1113
static void             NavUpdateCreateWrappingRequest();
1114
static void             NavEndFrame();
1115
static bool             NavScoreItem(ImGuiNavItemData* result);
1116
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1117
static void             NavProcessItem();
1118
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1119
static ImVec2           NavCalcPreferredRefPos();
1120
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1121
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1122
static void             NavRestoreLayer(ImGuiNavLayer layer);
1123
static int              FindWindowFocusIndex(ImGuiWindow* window);
1124
1125
// Error Checking and Debug Tools
1126
static void             ErrorCheckNewFrameSanityChecks();
1127
static void             ErrorCheckEndFrameSanityChecks();
1128
static void             UpdateDebugToolItemPicker();
1129
static void             UpdateDebugToolStackQueries();
1130
static void             UpdateDebugToolFlashStyleColor();
1131
1132
// Inputs
1133
static void             UpdateKeyboardInputs();
1134
static void             UpdateMouseInputs();
1135
static void             UpdateMouseWheel();
1136
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1137
1138
// Misc
1139
static void             UpdateSettings();
1140
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1141
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1142
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1143
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1144
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1145
static void             RenderDimmedBackgrounds();
1146
1147
// Viewports
1148
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1149
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1150
static void             DestroyViewport(ImGuiViewportP* viewport);
1151
static void             UpdateViewportsNewFrame();
1152
static void             UpdateViewportsEndFrame();
1153
static void             WindowSelectViewport(ImGuiWindow* window);
1154
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1155
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1156
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1157
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1158
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1159
static int              FindPlatformMonitorForRect(const ImRect& r);
1160
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1161
1162
}
1163
1164
//-----------------------------------------------------------------------------
1165
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1166
//-----------------------------------------------------------------------------
1167
1168
// DLL users:
1169
// - Heaps and globals are not shared across DLL boundaries!
1170
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1171
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1172
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1173
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1174
1175
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1176
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1177
//   Change to a different context by calling ImGui::SetCurrentContext().
1178
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1179
//   If you want thread-safety to allow N threads to access N different contexts:
1180
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1181
//         struct ImGuiContext;
1182
//         extern thread_local ImGuiContext* MyImGuiTLS;
1183
//         #define GImGui MyImGuiTLS
1184
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1185
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1186
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1187
// - DLL users: read comments above.
1188
#ifndef GImGui
1189
ImGuiContext*   GImGui = NULL;
1190
#endif
1191
1192
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1193
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1194
// - DLL users: read comments above.
1195
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1196
1.19k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1197
1.15k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1198
#else
1199
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1200
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1201
#endif
1202
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1203
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1204
static void*                GImAllocatorUserData = NULL;
1205
1206
//-----------------------------------------------------------------------------
1207
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1208
//-----------------------------------------------------------------------------
1209
1210
ImGuiStyle::ImGuiStyle()
1211
1
{
1212
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1213
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1214
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1215
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1216
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1217
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1218
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1219
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1220
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1221
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1222
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1223
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1224
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1225
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1226
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1227
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1228
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1229
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1230
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1231
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1232
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1233
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1234
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1235
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1236
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1237
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1238
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1239
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1240
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1241
1
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1242
1
    TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1243
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1244
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1245
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1246
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1247
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1248
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1249
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1250
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1251
1
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1252
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1253
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1254
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1255
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1256
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1257
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1258
1259
    // Behaviors
1260
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1261
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1262
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1263
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1264
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1265
1266
    // Default theme
1267
1
    ImGui::StyleColorsDark(this);
1268
1
}
1269
1270
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1271
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1272
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1273
0
{
1274
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1275
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1276
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1277
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1278
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1279
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1280
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1281
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1282
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1283
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1284
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1285
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1286
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1287
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1288
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1289
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1290
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1291
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1292
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1293
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1294
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1295
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1296
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1297
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1298
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1299
0
}
1300
1301
ImGuiIO::ImGuiIO()
1302
1
{
1303
    // Most fields are initialized with zero
1304
1
    memset(this, 0, sizeof(*this));
1305
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1306
1307
    // Settings
1308
1
    ConfigFlags = ImGuiConfigFlags_None;
1309
1
    BackendFlags = ImGuiBackendFlags_None;
1310
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1311
1
    DeltaTime = 1.0f / 60.0f;
1312
1
    IniSavingRate = 5.0f;
1313
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1314
1
    LogFilename = "imgui_log.txt";
1315
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1316
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1317
        KeyMap[i] = -1;
1318
#endif
1319
1
    UserData = NULL;
1320
1321
1
    Fonts = NULL;
1322
1
    FontGlobalScale = 1.0f;
1323
1
    FontDefault = NULL;
1324
1
    FontAllowUserScaling = false;
1325
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1326
1327
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1328
1
    ConfigDockingNoSplit = false;
1329
1
    ConfigDockingWithShift = false;
1330
1
    ConfigDockingAlwaysTabBar = false;
1331
1
    ConfigDockingTransparentPayload = false;
1332
1333
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1334
1
    ConfigViewportsNoAutoMerge = false;
1335
1
    ConfigViewportsNoTaskBarIcon = false;
1336
1
    ConfigViewportsNoDecoration = true;
1337
1
    ConfigViewportsNoDefaultParent = false;
1338
1339
    // Miscellaneous options
1340
1
    MouseDrawCursor = false;
1341
#ifdef __APPLE__
1342
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1343
#else
1344
1
    ConfigMacOSXBehaviors = false;
1345
1
#endif
1346
1
    ConfigInputTrickleEventQueue = true;
1347
1
    ConfigInputTextCursorBlink = true;
1348
1
    ConfigInputTextEnterKeepActive = false;
1349
1
    ConfigDragClickToInputText = false;
1350
1
    ConfigWindowsResizeFromEdges = true;
1351
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1352
1
    ConfigMemoryCompactTimer = 60.0f;
1353
1
    ConfigDebugBeginReturnValueOnce = false;
1354
1
    ConfigDebugBeginReturnValueLoop = false;
1355
1356
    // Inputs Behaviors
1357
1
    MouseDoubleClickTime = 0.30f;
1358
1
    MouseDoubleClickMaxDist = 6.0f;
1359
1
    MouseDragThreshold = 6.0f;
1360
1
    KeyRepeatDelay = 0.275f;
1361
1
    KeyRepeatRate = 0.050f;
1362
1363
    // Platform Functions
1364
    // Note: Initialize() will setup default clipboard/ime handlers.
1365
1
    BackendPlatformName = BackendRendererName = NULL;
1366
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1367
1
    PlatformLocaleDecimalPoint = '.';
1368
1369
    // Input (NB: we already have memset zero the entire structure!)
1370
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1371
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1372
1
    MouseSource = ImGuiMouseSource_Mouse;
1373
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1374
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1375
1
    AppAcceptingEvents = true;
1376
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1377
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1378
1
}
1379
1380
// Pass in translated ASCII characters for text input.
1381
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1382
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1383
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1384
void ImGuiIO::AddInputCharacter(unsigned int c)
1385
3.61k
{
1386
3.61k
    IM_ASSERT(Ctx != NULL);
1387
3.61k
    ImGuiContext& g = *Ctx;
1388
3.61k
    if (c == 0 || !AppAcceptingEvents)
1389
1.23k
        return;
1390
1391
2.38k
    ImGuiInputEvent e;
1392
2.38k
    e.Type = ImGuiInputEventType_Text;
1393
2.38k
    e.Source = ImGuiInputSource_Keyboard;
1394
2.38k
    e.EventId = g.InputEventsNextEventId++;
1395
2.38k
    e.Text.Char = c;
1396
2.38k
    g.InputEventsQueue.push_back(e);
1397
2.38k
}
1398
1399
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1400
// we should save the high surrogate.
1401
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1402
2.10k
{
1403
2.10k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1404
222
        return;
1405
1406
1.88k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1407
886
    {
1408
886
        if (InputQueueSurrogate != 0)
1409
340
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1410
886
        InputQueueSurrogate = c;
1411
886
        return;
1412
886
    }
1413
1414
996
    ImWchar cp = c;
1415
996
    if (InputQueueSurrogate != 0)
1416
504
    {
1417
504
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1418
282
        {
1419
282
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1420
282
        }
1421
222
        else
1422
222
        {
1423
222
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1424
222
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1425
#else
1426
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1427
#endif
1428
222
        }
1429
1430
504
        InputQueueSurrogate = 0;
1431
504
    }
1432
996
    AddInputCharacter((unsigned)cp);
1433
996
}
1434
1435
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1436
66
{
1437
66
    if (!AppAcceptingEvents)
1438
0
        return;
1439
66
    while (*utf8_chars != 0)
1440
0
    {
1441
0
        unsigned int c = 0;
1442
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1443
0
        AddInputCharacter(c);
1444
0
    }
1445
66
}
1446
1447
// Clear all incoming events.
1448
void ImGuiIO::ClearEventsQueue()
1449
0
{
1450
0
    IM_ASSERT(Ctx != NULL);
1451
0
    ImGuiContext& g = *Ctx;
1452
0
    g.InputEventsQueue.clear();
1453
0
}
1454
1455
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1456
void ImGuiIO::ClearInputKeys()
1457
6.00k
{
1458
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1459
    memset(KeysDown, 0, sizeof(KeysDown));
1460
#endif
1461
930k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1462
924k
    {
1463
924k
        KeysData[n].Down             = false;
1464
924k
        KeysData[n].DownDuration     = -1.0f;
1465
924k
        KeysData[n].DownDurationPrev = -1.0f;
1466
924k
    }
1467
6.00k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1468
6.00k
    KeyMods = ImGuiMod_None;
1469
6.00k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1470
36.0k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1471
30.0k
    {
1472
30.0k
        MouseDown[n] = false;
1473
30.0k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1474
30.0k
    }
1475
6.00k
    MouseWheel = MouseWheelH = 0.0f;
1476
6.00k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1477
6.00k
}
1478
1479
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1480
// Current frame character buffer is now also cleared by ClearInputKeys().
1481
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1482
void ImGuiIO::ClearInputCharacters()
1483
{
1484
    InputQueueCharacters.resize(0);
1485
}
1486
#endif
1487
1488
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1489
10.5k
{
1490
10.5k
    ImGuiContext& g = *ctx;
1491
18.1k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1492
11.5k
    {
1493
11.5k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1494
11.5k
        if (e->Type != type)
1495
4.79k
            continue;
1496
6.79k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1497
1.13k
            continue;
1498
5.66k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1499
1.61k
            continue;
1500
4.05k
        return e;
1501
5.66k
    }
1502
6.53k
    return NULL;
1503
10.5k
}
1504
1505
// Queue a new key down/up event.
1506
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1507
// - bool down:          Is the key down? use false to signify a key release.
1508
// - float analog_value: 0.0f..1.0f
1509
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1510
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1511
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1512
3.07k
{
1513
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1514
3.07k
    IM_ASSERT(Ctx != NULL);
1515
3.07k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1516
0
        return;
1517
3.07k
    ImGuiContext& g = *Ctx;
1518
3.07k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1519
3.07k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1520
3.07k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1521
1522
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1523
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1524
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1525
    if (BackendUsingLegacyKeyArrays == -1)
1526
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1527
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1528
    BackendUsingLegacyKeyArrays = 0;
1529
#endif
1530
3.07k
    if (ImGui::IsGamepadKey(key))
1531
24
        BackendUsingLegacyNavInputArray = false;
1532
1533
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1534
3.07k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1535
3.07k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1536
3.07k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1537
3.07k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1538
3.07k
    if (latest_key_down == down && latest_key_analog == analog_value)
1539
263
        return;
1540
1541
    // Add event
1542
2.81k
    ImGuiInputEvent e;
1543
2.81k
    e.Type = ImGuiInputEventType_Key;
1544
2.81k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1545
2.81k
    e.EventId = g.InputEventsNextEventId++;
1546
2.81k
    e.Key.Key = key;
1547
2.81k
    e.Key.Down = down;
1548
2.81k
    e.Key.AnalogValue = analog_value;
1549
2.81k
    g.InputEventsQueue.push_back(e);
1550
2.81k
}
1551
1552
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1553
426
{
1554
426
    if (!AppAcceptingEvents)
1555
0
        return;
1556
426
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1557
426
}
1558
1559
// [Optional] Call after AddKeyEvent().
1560
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1561
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1562
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1563
0
{
1564
0
    if (key == ImGuiKey_None)
1565
0
        return;
1566
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1567
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1568
0
    IM_UNUSED(native_keycode);  // Yet unused
1569
0
    IM_UNUSED(native_scancode); // Yet unused
1570
1571
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1572
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1573
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1574
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1575
        return;
1576
    KeyMap[legacy_key] = key;
1577
    KeyMap[key] = legacy_key;
1578
#else
1579
0
    IM_UNUSED(key);
1580
0
    IM_UNUSED(native_legacy_index);
1581
0
#endif
1582
0
}
1583
1584
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1585
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1586
0
{
1587
0
    AppAcceptingEvents = accepting_events;
1588
0
}
1589
1590
// Queue a mouse move event
1591
void ImGuiIO::AddMousePosEvent(float x, float y)
1592
2.75k
{
1593
2.75k
    IM_ASSERT(Ctx != NULL);
1594
2.75k
    ImGuiContext& g = *Ctx;
1595
2.75k
    if (!AppAcceptingEvents)
1596
0
        return;
1597
1598
    // Apply same flooring as UpdateMouseInputs()
1599
2.75k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1600
1601
    // Filter duplicate
1602
2.75k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1603
2.75k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1604
2.75k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1605
538
        return;
1606
1607
2.21k
    ImGuiInputEvent e;
1608
2.21k
    e.Type = ImGuiInputEventType_MousePos;
1609
2.21k
    e.Source = ImGuiInputSource_Mouse;
1610
2.21k
    e.EventId = g.InputEventsNextEventId++;
1611
2.21k
    e.MousePos.PosX = pos.x;
1612
2.21k
    e.MousePos.PosY = pos.y;
1613
2.21k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1614
2.21k
    g.InputEventsQueue.push_back(e);
1615
2.21k
}
1616
1617
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1618
3.60k
{
1619
3.60k
    IM_ASSERT(Ctx != NULL);
1620
3.60k
    ImGuiContext& g = *Ctx;
1621
3.60k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1622
3.60k
    if (!AppAcceptingEvents)
1623
0
        return;
1624
1625
    // Filter duplicate
1626
3.60k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1627
3.60k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1628
3.60k
    if (latest_button_down == down)
1629
403
        return;
1630
1631
3.20k
    ImGuiInputEvent e;
1632
3.20k
    e.Type = ImGuiInputEventType_MouseButton;
1633
3.20k
    e.Source = ImGuiInputSource_Mouse;
1634
3.20k
    e.EventId = g.InputEventsNextEventId++;
1635
3.20k
    e.MouseButton.Button = mouse_button;
1636
3.20k
    e.MouseButton.Down = down;
1637
3.20k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1638
3.20k
    g.InputEventsQueue.push_back(e);
1639
3.20k
}
1640
1641
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1642
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1643
1.05k
{
1644
1.05k
    IM_ASSERT(Ctx != NULL);
1645
1.05k
    ImGuiContext& g = *Ctx;
1646
1647
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1648
1.05k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1649
24
        return;
1650
1651
1.03k
    ImGuiInputEvent e;
1652
1.03k
    e.Type = ImGuiInputEventType_MouseWheel;
1653
1.03k
    e.Source = ImGuiInputSource_Mouse;
1654
1.03k
    e.EventId = g.InputEventsNextEventId++;
1655
1.03k
    e.MouseWheel.WheelX = wheel_x;
1656
1.03k
    e.MouseWheel.WheelY = wheel_y;
1657
1.03k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1658
1.03k
    g.InputEventsQueue.push_back(e);
1659
1.03k
}
1660
1661
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1662
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1663
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1664
0
{
1665
0
    IM_ASSERT(Ctx != NULL);
1666
0
    ImGuiContext& g = *Ctx;
1667
0
    g.InputEventsNextMouseSource = source;
1668
0
}
1669
1670
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1671
0
{
1672
0
    IM_ASSERT(Ctx != NULL);
1673
0
    ImGuiContext& g = *Ctx;
1674
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1675
0
    if (!AppAcceptingEvents)
1676
0
        return;
1677
1678
    // Filter duplicate
1679
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1680
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1681
0
    if (latest_viewport_id == viewport_id)
1682
0
        return;
1683
1684
0
    ImGuiInputEvent e;
1685
0
    e.Type = ImGuiInputEventType_MouseViewport;
1686
0
    e.Source = ImGuiInputSource_Mouse;
1687
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1688
0
    g.InputEventsQueue.push_back(e);
1689
0
}
1690
1691
void ImGuiIO::AddFocusEvent(bool focused)
1692
1.14k
{
1693
1.14k
    IM_ASSERT(Ctx != NULL);
1694
1.14k
    ImGuiContext& g = *Ctx;
1695
1696
    // Filter duplicate
1697
1.14k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1698
1.14k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1699
1.14k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1700
138
        return;
1701
1702
1.00k
    ImGuiInputEvent e;
1703
1.00k
    e.Type = ImGuiInputEventType_Focus;
1704
1.00k
    e.EventId = g.InputEventsNextEventId++;
1705
1.00k
    e.AppFocused.Focused = focused;
1706
1.00k
    g.InputEventsQueue.push_back(e);
1707
1.00k
}
1708
1709
//-----------------------------------------------------------------------------
1710
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1711
//-----------------------------------------------------------------------------
1712
1713
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1714
0
{
1715
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1716
0
    ImVec2 p_last = p1;
1717
0
    ImVec2 p_closest;
1718
0
    float p_closest_dist2 = FLT_MAX;
1719
0
    float t_step = 1.0f / (float)num_segments;
1720
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1721
0
    {
1722
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1723
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1724
0
        float dist2 = ImLengthSqr(p - p_line);
1725
0
        if (dist2 < p_closest_dist2)
1726
0
        {
1727
0
            p_closest = p_line;
1728
0
            p_closest_dist2 = dist2;
1729
0
        }
1730
0
        p_last = p_current;
1731
0
    }
1732
0
    return p_closest;
1733
0
}
1734
1735
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1736
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1737
0
{
1738
0
    float dx = x4 - x1;
1739
0
    float dy = y4 - y1;
1740
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1741
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1742
0
    d2 = (d2 >= 0) ? d2 : -d2;
1743
0
    d3 = (d3 >= 0) ? d3 : -d3;
1744
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1745
0
    {
1746
0
        ImVec2 p_current(x4, y4);
1747
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1748
0
        float dist2 = ImLengthSqr(p - p_line);
1749
0
        if (dist2 < p_closest_dist2)
1750
0
        {
1751
0
            p_closest = p_line;
1752
0
            p_closest_dist2 = dist2;
1753
0
        }
1754
0
        p_last = p_current;
1755
0
    }
1756
0
    else if (level < 10)
1757
0
    {
1758
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1759
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1760
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1761
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1762
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1763
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1764
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1765
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1766
0
    }
1767
0
}
1768
1769
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1770
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1771
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1772
0
{
1773
0
    IM_ASSERT(tess_tol > 0.0f);
1774
0
    ImVec2 p_last = p1;
1775
0
    ImVec2 p_closest;
1776
0
    float p_closest_dist2 = FLT_MAX;
1777
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1778
0
    return p_closest;
1779
0
}
1780
1781
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1782
0
{
1783
0
    ImVec2 ap = p - a;
1784
0
    ImVec2 ab_dir = b - a;
1785
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1786
0
    if (dot < 0.0f)
1787
0
        return a;
1788
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1789
0
    if (dot > ab_len_sqr)
1790
0
        return b;
1791
0
    return a + ab_dir * dot / ab_len_sqr;
1792
0
}
1793
1794
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1795
0
{
1796
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1797
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1798
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1799
0
    return ((b1 == b2) && (b2 == b3));
1800
0
}
1801
1802
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1803
0
{
1804
0
    ImVec2 v0 = b - a;
1805
0
    ImVec2 v1 = c - a;
1806
0
    ImVec2 v2 = p - a;
1807
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1808
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1809
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1810
0
    out_u = 1.0f - out_v - out_w;
1811
0
}
1812
1813
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1814
0
{
1815
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1816
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1817
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1818
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1819
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1820
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1821
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1822
0
    if (m == dist2_ab)
1823
0
        return proj_ab;
1824
0
    if (m == dist2_bc)
1825
0
        return proj_bc;
1826
0
    return proj_ca;
1827
0
}
1828
1829
//-----------------------------------------------------------------------------
1830
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1831
//-----------------------------------------------------------------------------
1832
1833
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1834
int ImStricmp(const char* str1, const char* str2)
1835
0
{
1836
0
    int d;
1837
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1838
0
    return d;
1839
0
}
1840
1841
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1842
0
{
1843
0
    int d = 0;
1844
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1845
0
    return d;
1846
0
}
1847
1848
void ImStrncpy(char* dst, const char* src, size_t count)
1849
0
{
1850
0
    if (count < 1)
1851
0
        return;
1852
0
    if (count > 1)
1853
0
        strncpy(dst, src, count - 1);
1854
0
    dst[count - 1] = 0;
1855
0
}
1856
1857
char* ImStrdup(const char* str)
1858
3
{
1859
3
    size_t len = strlen(str);
1860
3
    void* buf = IM_ALLOC(len + 1);
1861
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1862
3
}
1863
1864
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1865
0
{
1866
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1867
0
    size_t src_size = strlen(src) + 1;
1868
0
    if (dst_buf_size < src_size)
1869
0
    {
1870
0
        IM_FREE(dst);
1871
0
        dst = (char*)IM_ALLOC(src_size);
1872
0
        if (p_dst_size)
1873
0
            *p_dst_size = src_size;
1874
0
    }
1875
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1876
0
}
1877
1878
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1879
0
{
1880
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1881
0
    return p;
1882
0
}
1883
1884
int ImStrlenW(const ImWchar* str)
1885
0
{
1886
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1887
0
    int n = 0;
1888
0
    while (*str++) n++;
1889
0
    return n;
1890
0
}
1891
1892
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1893
const char* ImStreolRange(const char* str, const char* str_end)
1894
0
{
1895
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1896
0
    return p ? p : str_end;
1897
0
}
1898
1899
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1900
0
{
1901
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1902
0
        buf_mid_line--;
1903
0
    return buf_mid_line;
1904
0
}
1905
1906
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1907
0
{
1908
0
    if (!needle_end)
1909
0
        needle_end = needle + strlen(needle);
1910
1911
0
    const char un0 = (char)ImToUpper(*needle);
1912
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1913
0
    {
1914
0
        if (ImToUpper(*haystack) == un0)
1915
0
        {
1916
0
            const char* b = needle + 1;
1917
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1918
0
                if (ImToUpper(*a) != ImToUpper(*b))
1919
0
                    break;
1920
0
            if (b == needle_end)
1921
0
                return haystack;
1922
0
        }
1923
0
        haystack++;
1924
0
    }
1925
0
    return NULL;
1926
0
}
1927
1928
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1929
void ImStrTrimBlanks(char* buf)
1930
0
{
1931
0
    char* p = buf;
1932
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1933
0
        p++;
1934
0
    char* p_start = p;
1935
0
    while (*p != 0)                         // Find end of string
1936
0
        p++;
1937
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1938
0
        p--;
1939
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1940
0
        memmove(buf, p_start, p - p_start);
1941
0
    buf[p - p_start] = 0;                   // Zero terminate
1942
0
}
1943
1944
const char* ImStrSkipBlank(const char* str)
1945
0
{
1946
0
    while (str[0] == ' ' || str[0] == '\t')
1947
0
        str++;
1948
0
    return str;
1949
0
}
1950
1951
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1952
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1953
// B) When buf==NULL vsnprintf() will return the output size.
1954
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1955
1956
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1957
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1958
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1959
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1960
#ifdef IMGUI_USE_STB_SPRINTF
1961
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1962
#define STB_SPRINTF_IMPLEMENTATION
1963
#endif
1964
#ifdef IMGUI_STB_SPRINTF_FILENAME
1965
#include IMGUI_STB_SPRINTF_FILENAME
1966
#else
1967
#include "stb_sprintf.h"
1968
#endif
1969
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1970
1971
#if defined(_MSC_VER) && !defined(vsnprintf)
1972
#define vsnprintf _vsnprintf
1973
#endif
1974
1975
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1976
1
{
1977
1
    va_list args;
1978
1
    va_start(args, fmt);
1979
#ifdef IMGUI_USE_STB_SPRINTF
1980
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1981
#else
1982
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1983
1
#endif
1984
1
    va_end(args);
1985
1
    if (buf == NULL)
1986
0
        return w;
1987
1
    if (w == -1 || w >= (int)buf_size)
1988
0
        w = (int)buf_size - 1;
1989
1
    buf[w] = 0;
1990
1
    return w;
1991
1
}
1992
1993
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1994
435
{
1995
#ifdef IMGUI_USE_STB_SPRINTF
1996
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1997
#else
1998
435
    int w = vsnprintf(buf, buf_size, fmt, args);
1999
435
#endif
2000
435
    if (buf == NULL)
2001
0
        return w;
2002
435
    if (w == -1 || w >= (int)buf_size)
2003
0
        w = (int)buf_size - 1;
2004
435
    buf[w] = 0;
2005
435
    return w;
2006
435
}
2007
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2008
2009
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2010
435
{
2011
435
    va_list args;
2012
435
    va_start(args, fmt);
2013
435
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2014
435
    va_end(args);
2015
435
}
2016
2017
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2018
435
{
2019
435
    ImGuiContext& g = *GImGui;
2020
435
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2021
0
    {
2022
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2023
0
        if (buf == NULL)
2024
0
            buf = "(null)";
2025
0
        *out_buf = buf;
2026
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2027
0
    }
2028
435
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2029
0
    {
2030
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2031
0
        const char* buf = va_arg(args, const char*);
2032
0
        if (buf == NULL)
2033
0
        {
2034
0
            buf = "(null)";
2035
0
            buf_len = ImMin(buf_len, 6);
2036
0
        }
2037
0
        *out_buf = buf;
2038
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2039
0
    }
2040
435
    else
2041
435
    {
2042
435
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2043
435
        *out_buf = g.TempBuffer.Data;
2044
435
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2045
435
    }
2046
435
}
2047
2048
// CRC32 needs a 1KB lookup table (not cache friendly)
2049
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2050
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2051
static const ImU32 GCrc32LookupTable[256] =
2052
{
2053
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2054
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2055
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2056
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2057
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2058
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2059
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2060
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2061
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2062
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2063
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2064
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2065
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2066
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2067
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2068
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2069
};
2070
2071
// Known size hash
2072
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2073
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2074
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2075
433
{
2076
433
    ImU32 crc = ~seed;
2077
433
    const unsigned char* data = (const unsigned char*)data_p;
2078
433
    const ImU32* crc32_lut = GCrc32LookupTable;
2079
2.16k
    while (data_size-- != 0)
2080
1.73k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2081
433
    return ~crc;
2082
433
}
2083
2084
// Zero-terminated string hash, with support for ### to reset back to seed value
2085
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2086
// Because this syntax is rarely used we are optimizing for the common case.
2087
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2088
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2089
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2090
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2091
113k
{
2092
113k
    seed = ~seed;
2093
113k
    ImU32 crc = seed;
2094
113k
    const unsigned char* data = (const unsigned char*)data_p;
2095
113k
    const ImU32* crc32_lut = GCrc32LookupTable;
2096
113k
    if (data_size != 0)
2097
0
    {
2098
0
        while (data_size-- != 0)
2099
0
        {
2100
0
            unsigned char c = *data++;
2101
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2102
0
                crc = seed;
2103
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2104
0
        }
2105
0
    }
2106
113k
    else
2107
113k
    {
2108
1.56M
        while (unsigned char c = *data++)
2109
1.45M
        {
2110
1.45M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2111
22.2k
                crc = seed;
2112
1.45M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2113
1.45M
        }
2114
113k
    }
2115
113k
    return ~crc;
2116
113k
}
2117
2118
//-----------------------------------------------------------------------------
2119
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2120
//-----------------------------------------------------------------------------
2121
2122
// Default file functions
2123
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2124
2125
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2126
0
{
2127
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2128
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2129
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2130
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2131
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2132
2133
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2134
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2135
    wchar_t local_temp_stack[FILENAME_MAX];
2136
    ImVector<wchar_t> local_temp_heap;
2137
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2138
        local_temp_heap.resize(filename_wsize + mode_wsize);
2139
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2140
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2141
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2142
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2143
    return ::_wfopen(filename_wbuf, mode_wbuf);
2144
#else
2145
0
    return fopen(filename, mode);
2146
0
#endif
2147
0
}
2148
2149
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2150
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2151
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2152
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2153
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2154
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2155
2156
// Helper: Load file content into memory
2157
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2158
// This can't really be used with "rt" because fseek size won't match read size.
2159
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2160
0
{
2161
0
    IM_ASSERT(filename && mode);
2162
0
    if (out_file_size)
2163
0
        *out_file_size = 0;
2164
2165
0
    ImFileHandle f;
2166
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2167
0
        return NULL;
2168
2169
0
    size_t file_size = (size_t)ImFileGetSize(f);
2170
0
    if (file_size == (size_t)-1)
2171
0
    {
2172
0
        ImFileClose(f);
2173
0
        return NULL;
2174
0
    }
2175
2176
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2177
0
    if (file_data == NULL)
2178
0
    {
2179
0
        ImFileClose(f);
2180
0
        return NULL;
2181
0
    }
2182
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2183
0
    {
2184
0
        ImFileClose(f);
2185
0
        IM_FREE(file_data);
2186
0
        return NULL;
2187
0
    }
2188
0
    if (padding_bytes > 0)
2189
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2190
2191
0
    ImFileClose(f);
2192
0
    if (out_file_size)
2193
0
        *out_file_size = file_size;
2194
2195
0
    return file_data;
2196
0
}
2197
2198
//-----------------------------------------------------------------------------
2199
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2200
//-----------------------------------------------------------------------------
2201
2202
IM_MSVC_RUNTIME_CHECKS_OFF
2203
2204
// Convert UTF-8 to 32-bit character, process single character input.
2205
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2206
// We handle UTF-8 decoding error by skipping forward.
2207
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2208
31
{
2209
31
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2210
31
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2211
31
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2212
31
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2213
31
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2214
31
    int len = lengths[*(const unsigned char*)in_text >> 3];
2215
31
    int wanted = len + (len ? 0 : 1);
2216
2217
31
    if (in_text_end == NULL)
2218
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2219
2220
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2221
    // so it is fast even with excessive branching.
2222
31
    unsigned char s[4];
2223
31
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2224
31
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2225
31
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2226
31
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2227
2228
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2229
31
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2230
31
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2231
31
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2232
31
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2233
31
    *out_char >>= shiftc[len];
2234
2235
    // Accumulate the various error conditions.
2236
31
    int e = 0;
2237
31
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2238
31
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2239
31
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2240
31
    e |= (s[1] & 0xc0) >> 2;
2241
31
    e |= (s[2] & 0xc0) >> 4;
2242
31
    e |= (s[3]       ) >> 6;
2243
31
    e ^= 0x2a; // top two bits of each tail byte correct?
2244
31
    e >>= shifte[len];
2245
2246
31
    if (e)
2247
5
    {
2248
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2249
        // One byte is consumed in case of invalid first byte of in_text.
2250
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2251
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2252
5
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2253
5
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2254
5
    }
2255
2256
31
    return wanted;
2257
31
}
2258
2259
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2260
0
{
2261
0
    ImWchar* buf_out = buf;
2262
0
    ImWchar* buf_end = buf + buf_size;
2263
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2264
0
    {
2265
0
        unsigned int c;
2266
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2267
0
        *buf_out++ = (ImWchar)c;
2268
0
    }
2269
0
    *buf_out = 0;
2270
0
    if (in_text_remaining)
2271
0
        *in_text_remaining = in_text;
2272
0
    return (int)(buf_out - buf);
2273
0
}
2274
2275
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2276
0
{
2277
0
    int char_count = 0;
2278
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2279
0
    {
2280
0
        unsigned int c;
2281
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2282
0
        char_count++;
2283
0
    }
2284
0
    return char_count;
2285
0
}
2286
2287
// Based on stb_to_utf8() from github.com/nothings/stb/
2288
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2289
0
{
2290
0
    if (c < 0x80)
2291
0
    {
2292
0
        buf[0] = (char)c;
2293
0
        return 1;
2294
0
    }
2295
0
    if (c < 0x800)
2296
0
    {
2297
0
        if (buf_size < 2) return 0;
2298
0
        buf[0] = (char)(0xc0 + (c >> 6));
2299
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2300
0
        return 2;
2301
0
    }
2302
0
    if (c < 0x10000)
2303
0
    {
2304
0
        if (buf_size < 3) return 0;
2305
0
        buf[0] = (char)(0xe0 + (c >> 12));
2306
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2307
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2308
0
        return 3;
2309
0
    }
2310
0
    if (c <= 0x10FFFF)
2311
0
    {
2312
0
        if (buf_size < 4) return 0;
2313
0
        buf[0] = (char)(0xf0 + (c >> 18));
2314
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2315
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2316
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2317
0
        return 4;
2318
0
    }
2319
    // Invalid code point, the max unicode is 0x10FFFF
2320
0
    return 0;
2321
0
}
2322
2323
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2324
0
{
2325
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2326
0
    out_buf[count] = 0;
2327
0
    return out_buf;
2328
0
}
2329
2330
// Not optimal but we very rarely use this function.
2331
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2332
0
{
2333
0
    unsigned int unused = 0;
2334
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2335
0
}
2336
2337
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2338
0
{
2339
0
    if (c < 0x80) return 1;
2340
0
    if (c < 0x800) return 2;
2341
0
    if (c < 0x10000) return 3;
2342
0
    if (c <= 0x10FFFF) return 4;
2343
0
    return 3;
2344
0
}
2345
2346
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2347
0
{
2348
0
    char* buf_p = out_buf;
2349
0
    const char* buf_end = out_buf + out_buf_size;
2350
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2351
0
    {
2352
0
        unsigned int c = (unsigned int)(*in_text++);
2353
0
        if (c < 0x80)
2354
0
            *buf_p++ = (char)c;
2355
0
        else
2356
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2357
0
    }
2358
0
    *buf_p = 0;
2359
0
    return (int)(buf_p - out_buf);
2360
0
}
2361
2362
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2363
0
{
2364
0
    int bytes_count = 0;
2365
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2366
0
    {
2367
0
        unsigned int c = (unsigned int)(*in_text++);
2368
0
        if (c < 0x80)
2369
0
            bytes_count++;
2370
0
        else
2371
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2372
0
    }
2373
0
    return bytes_count;
2374
0
}
2375
2376
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2377
0
{
2378
0
    while (in_text_curr > in_text_start)
2379
0
    {
2380
0
        in_text_curr--;
2381
0
        if ((*in_text_curr & 0xC0) != 0x80)
2382
0
            return in_text_curr;
2383
0
    }
2384
0
    return in_text_start;
2385
0
}
2386
2387
IM_MSVC_RUNTIME_CHECKS_RESTORE
2388
2389
//-----------------------------------------------------------------------------
2390
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2391
// Note: The Convert functions are early design which are not consistent with other API.
2392
//-----------------------------------------------------------------------------
2393
2394
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2395
0
{
2396
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2397
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2398
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2399
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2400
0
    return IM_COL32(r, g, b, 0xFF);
2401
0
}
2402
2403
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2404
93.1k
{
2405
93.1k
    float s = 1.0f / 255.0f;
2406
93.1k
    return ImVec4(
2407
93.1k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2408
93.1k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2409
93.1k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2410
93.1k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2411
93.1k
}
2412
2413
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2414
339k
{
2415
339k
    ImU32 out;
2416
339k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2417
339k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2418
339k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2419
339k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2420
339k
    return out;
2421
339k
}
2422
2423
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2424
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2425
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2426
0
{
2427
0
    float K = 0.f;
2428
0
    if (g < b)
2429
0
    {
2430
0
        ImSwap(g, b);
2431
0
        K = -1.f;
2432
0
    }
2433
0
    if (r < g)
2434
0
    {
2435
0
        ImSwap(r, g);
2436
0
        K = -2.f / 6.f - K;
2437
0
    }
2438
2439
0
    const float chroma = r - (g < b ? g : b);
2440
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2441
0
    out_s = chroma / (r + 1e-20f);
2442
0
    out_v = r;
2443
0
}
2444
2445
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2446
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2447
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2448
0
{
2449
0
    if (s == 0.0f)
2450
0
    {
2451
        // gray
2452
0
        out_r = out_g = out_b = v;
2453
0
        return;
2454
0
    }
2455
2456
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2457
0
    int   i = (int)h;
2458
0
    float f = h - (float)i;
2459
0
    float p = v * (1.0f - s);
2460
0
    float q = v * (1.0f - s * f);
2461
0
    float t = v * (1.0f - s * (1.0f - f));
2462
2463
0
    switch (i)
2464
0
    {
2465
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2466
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2467
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2468
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2469
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2470
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2471
0
    }
2472
0
}
2473
2474
//-----------------------------------------------------------------------------
2475
// [SECTION] ImGuiStorage
2476
// Helper: Key->value storage
2477
//-----------------------------------------------------------------------------
2478
2479
// std::lower_bound but without the bullshit
2480
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2481
44.8k
{
2482
44.8k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2483
44.8k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2484
44.8k
    size_t count = (size_t)(last - first);
2485
134k
    while (count > 0)
2486
89.7k
    {
2487
89.7k
        size_t count2 = count >> 1;
2488
89.7k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2489
89.7k
        if (mid->key < key)
2490
22.6k
        {
2491
22.6k
            first = ++mid;
2492
22.6k
            count -= count2 + 1;
2493
22.6k
        }
2494
67.0k
        else
2495
67.0k
        {
2496
67.0k
            count = count2;
2497
67.0k
        }
2498
89.7k
    }
2499
44.8k
    return first;
2500
44.8k
}
2501
2502
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2503
void ImGuiStorage::BuildSortByKey()
2504
0
{
2505
0
    struct StaticFunc
2506
0
    {
2507
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2508
0
        {
2509
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2510
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2511
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2512
0
            return 0;
2513
0
        }
2514
0
    };
2515
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2516
0
}
2517
2518
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2519
0
{
2520
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2521
0
    if (it == Data.end() || it->key != key)
2522
0
        return default_val;
2523
0
    return it->val_i;
2524
0
}
2525
2526
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2527
0
{
2528
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2529
0
}
2530
2531
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2532
0
{
2533
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2534
0
    if (it == Data.end() || it->key != key)
2535
0
        return default_val;
2536
0
    return it->val_f;
2537
0
}
2538
2539
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2540
44.8k
{
2541
44.8k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2542
44.8k
    if (it == Data.end() || it->key != key)
2543
3
        return NULL;
2544
44.8k
    return it->val_p;
2545
44.8k
}
2546
2547
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2548
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2549
0
{
2550
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2551
0
    if (it == Data.end() || it->key != key)
2552
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2553
0
    return &it->val_i;
2554
0
}
2555
2556
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2557
0
{
2558
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2559
0
}
2560
2561
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2562
0
{
2563
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2564
0
    if (it == Data.end() || it->key != key)
2565
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2566
0
    return &it->val_f;
2567
0
}
2568
2569
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2570
0
{
2571
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2572
0
    if (it == Data.end() || it->key != key)
2573
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2574
0
    return &it->val_p;
2575
0
}
2576
2577
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2578
void ImGuiStorage::SetInt(ImGuiID key, int val)
2579
0
{
2580
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2581
0
    if (it == Data.end() || it->key != key)
2582
0
        Data.insert(it, ImGuiStoragePair(key, val));
2583
0
    else
2584
0
        it->val_i = val;
2585
0
}
2586
2587
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2588
0
{
2589
0
    SetInt(key, val ? 1 : 0);
2590
0
}
2591
2592
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2593
0
{
2594
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2595
0
    if (it == Data.end() || it->key != key)
2596
0
        Data.insert(it, ImGuiStoragePair(key, val));
2597
0
    else
2598
0
        it->val_f = val;
2599
0
}
2600
2601
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2602
3
{
2603
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2604
3
    if (it == Data.end() || it->key != key)
2605
3
        Data.insert(it, ImGuiStoragePair(key, val));
2606
0
    else
2607
0
        it->val_p = val;
2608
3
}
2609
2610
void ImGuiStorage::SetAllInt(int v)
2611
0
{
2612
0
    for (int i = 0; i < Data.Size; i++)
2613
0
        Data[i].val_i = v;
2614
0
}
2615
2616
//-----------------------------------------------------------------------------
2617
// [SECTION] ImGuiTextFilter
2618
//-----------------------------------------------------------------------------
2619
2620
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2621
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2622
0
{
2623
0
    InputBuf[0] = 0;
2624
0
    CountGrep = 0;
2625
0
    if (default_filter)
2626
0
    {
2627
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2628
0
        Build();
2629
0
    }
2630
0
}
2631
2632
bool ImGuiTextFilter::Draw(const char* label, float width)
2633
0
{
2634
0
    if (width != 0.0f)
2635
0
        ImGui::SetNextItemWidth(width);
2636
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2637
0
    if (value_changed)
2638
0
        Build();
2639
0
    return value_changed;
2640
0
}
2641
2642
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2643
0
{
2644
0
    out->resize(0);
2645
0
    const char* wb = b;
2646
0
    const char* we = wb;
2647
0
    while (we < e)
2648
0
    {
2649
0
        if (*we == separator)
2650
0
        {
2651
0
            out->push_back(ImGuiTextRange(wb, we));
2652
0
            wb = we + 1;
2653
0
        }
2654
0
        we++;
2655
0
    }
2656
0
    if (wb != we)
2657
0
        out->push_back(ImGuiTextRange(wb, we));
2658
0
}
2659
2660
void ImGuiTextFilter::Build()
2661
0
{
2662
0
    Filters.resize(0);
2663
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2664
0
    input_range.split(',', &Filters);
2665
2666
0
    CountGrep = 0;
2667
0
    for (ImGuiTextRange& f : Filters)
2668
0
    {
2669
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2670
0
            f.b++;
2671
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2672
0
            f.e--;
2673
0
        if (f.empty())
2674
0
            continue;
2675
0
        if (f.b[0] != '-')
2676
0
            CountGrep += 1;
2677
0
    }
2678
0
}
2679
2680
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2681
0
{
2682
0
    if (Filters.empty())
2683
0
        return true;
2684
2685
0
    if (text == NULL)
2686
0
        text = "";
2687
2688
0
    for (const ImGuiTextRange& f : Filters)
2689
0
    {
2690
0
        if (f.empty())
2691
0
            continue;
2692
0
        if (f.b[0] == '-')
2693
0
        {
2694
            // Subtract
2695
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2696
0
                return false;
2697
0
        }
2698
0
        else
2699
0
        {
2700
            // Grep
2701
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2702
0
                return true;
2703
0
        }
2704
0
    }
2705
2706
    // Implicit * grep
2707
0
    if (CountGrep == 0)
2708
0
        return true;
2709
2710
0
    return false;
2711
0
}
2712
2713
//-----------------------------------------------------------------------------
2714
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2715
//-----------------------------------------------------------------------------
2716
2717
// On some platform vsnprintf() takes va_list by reference and modifies it.
2718
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2719
#ifndef va_copy
2720
#if defined(__GNUC__) || defined(__clang__)
2721
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2722
#else
2723
#define va_copy(dest, src) (dest = src)
2724
#endif
2725
#endif
2726
2727
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2728
2729
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2730
0
{
2731
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2732
2733
    // Add zero-terminator the first time
2734
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2735
0
    const int needed_sz = write_off + len;
2736
0
    if (write_off + len >= Buf.Capacity)
2737
0
    {
2738
0
        int new_capacity = Buf.Capacity * 2;
2739
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2740
0
    }
2741
2742
0
    Buf.resize(needed_sz);
2743
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2744
0
    Buf[write_off - 1 + len] = 0;
2745
0
}
2746
2747
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2748
0
{
2749
0
    va_list args;
2750
0
    va_start(args, fmt);
2751
0
    appendfv(fmt, args);
2752
0
    va_end(args);
2753
0
}
2754
2755
// Helper: Text buffer for logging/accumulating text
2756
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2757
0
{
2758
0
    va_list args_copy;
2759
0
    va_copy(args_copy, args);
2760
2761
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2762
0
    if (len <= 0)
2763
0
    {
2764
0
        va_end(args_copy);
2765
0
        return;
2766
0
    }
2767
2768
    // Add zero-terminator the first time
2769
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2770
0
    const int needed_sz = write_off + len;
2771
0
    if (write_off + len >= Buf.Capacity)
2772
0
    {
2773
0
        int new_capacity = Buf.Capacity * 2;
2774
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2775
0
    }
2776
2777
0
    Buf.resize(needed_sz);
2778
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2779
0
    va_end(args_copy);
2780
0
}
2781
2782
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2783
0
{
2784
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2785
0
    if (old_size == new_size)
2786
0
        return;
2787
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2788
0
        LineOffsets.push_back(EndOffset);
2789
0
    const char* base_end = base + new_size;
2790
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2791
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2792
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2793
0
    EndOffset = ImMax(EndOffset, new_size);
2794
0
}
2795
2796
//-----------------------------------------------------------------------------
2797
// [SECTION] ImGuiListClipper
2798
//-----------------------------------------------------------------------------
2799
2800
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2801
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2802
static bool GetSkipItemForListClipping()
2803
0
{
2804
0
    ImGuiContext& g = *GImGui;
2805
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2806
0
}
2807
2808
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2809
0
{
2810
0
    if (ranges.Size - offset <= 1)
2811
0
        return;
2812
2813
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2814
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2815
0
        for (int i = offset; i < sort_end + offset; ++i)
2816
0
            if (ranges[i].Min > ranges[i + 1].Min)
2817
0
                ImSwap(ranges[i], ranges[i + 1]);
2818
2819
    // Now fuse ranges together as much as possible.
2820
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2821
0
    {
2822
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2823
0
        if (ranges[i - 1].Max < ranges[i].Min)
2824
0
            continue;
2825
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2826
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2827
0
        ranges.erase(ranges.Data + i);
2828
0
        i--;
2829
0
    }
2830
0
}
2831
2832
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2833
0
{
2834
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2835
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2836
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2837
0
    ImGuiContext& g = *GImGui;
2838
0
    ImGuiWindow* window = g.CurrentWindow;
2839
0
    float off_y = pos_y - window->DC.CursorPos.y;
2840
0
    window->DC.CursorPos.y = pos_y;
2841
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2842
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2843
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2844
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2845
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2846
0
    if (ImGuiTable* table = g.CurrentTable)
2847
0
    {
2848
0
        if (table->IsInsideRow)
2849
0
            ImGui::TableEndRow(table);
2850
0
        table->RowPosY2 = window->DC.CursorPos.y;
2851
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2852
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2853
0
        table->RowBgColorCounter += row_increase;
2854
0
    }
2855
0
}
2856
2857
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2858
0
{
2859
    // StartPosY starts from ItemsFrozen hence the subtraction
2860
    // Perform the add and multiply with double to allow seeking through larger ranges
2861
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2862
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2863
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2864
0
}
2865
2866
ImGuiListClipper::ImGuiListClipper()
2867
0
{
2868
0
    memset(this, 0, sizeof(*this));
2869
0
}
2870
2871
ImGuiListClipper::~ImGuiListClipper()
2872
0
{
2873
0
    End();
2874
0
}
2875
2876
void ImGuiListClipper::Begin(int items_count, float items_height)
2877
0
{
2878
0
    if (Ctx == NULL)
2879
0
        Ctx = ImGui::GetCurrentContext();
2880
2881
0
    ImGuiContext& g = *Ctx;
2882
0
    ImGuiWindow* window = g.CurrentWindow;
2883
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2884
2885
0
    if (ImGuiTable* table = g.CurrentTable)
2886
0
        if (table->IsInsideRow)
2887
0
            ImGui::TableEndRow(table);
2888
2889
0
    StartPosY = window->DC.CursorPos.y;
2890
0
    ItemsHeight = items_height;
2891
0
    ItemsCount = items_count;
2892
0
    DisplayStart = -1;
2893
0
    DisplayEnd = 0;
2894
2895
    // Acquire temporary buffer
2896
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2897
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2898
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2899
0
    data->Reset(this);
2900
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2901
0
    TempData = data;
2902
0
}
2903
2904
void ImGuiListClipper::End()
2905
0
{
2906
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2907
0
    {
2908
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2909
0
        ImGuiContext& g = *Ctx;
2910
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2911
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2912
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2913
2914
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2915
0
        IM_ASSERT(data->ListClipper == this);
2916
0
        data->StepNo = data->Ranges.Size;
2917
0
        if (--g.ClipperTempDataStacked > 0)
2918
0
        {
2919
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2920
0
            data->ListClipper->TempData = data;
2921
0
        }
2922
0
        TempData = NULL;
2923
0
    }
2924
0
    ItemsCount = -1;
2925
0
}
2926
2927
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2928
0
{
2929
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2930
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2931
0
    IM_ASSERT(item_begin <= item_end);
2932
0
    if (item_begin < item_end)
2933
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2934
0
}
2935
2936
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2937
0
{
2938
0
    ImGuiContext& g = *clipper->Ctx;
2939
0
    ImGuiWindow* window = g.CurrentWindow;
2940
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2941
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2942
2943
0
    ImGuiTable* table = g.CurrentTable;
2944
0
    if (table && table->IsInsideRow)
2945
0
        ImGui::TableEndRow(table);
2946
2947
    // No items
2948
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2949
0
        return false;
2950
2951
    // While we are in frozen row state, keep displaying items one by one, unclipped
2952
    // FIXME: Could be stored as a table-agnostic state.
2953
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2954
0
    {
2955
0
        clipper->DisplayStart = data->ItemsFrozen;
2956
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2957
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2958
0
            data->ItemsFrozen++;
2959
0
        return true;
2960
0
    }
2961
2962
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2963
0
    bool calc_clipping = false;
2964
0
    if (data->StepNo == 0)
2965
0
    {
2966
0
        clipper->StartPosY = window->DC.CursorPos.y;
2967
0
        if (clipper->ItemsHeight <= 0.0f)
2968
0
        {
2969
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2970
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2971
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2972
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2973
0
            data->StepNo = 1;
2974
0
            return true;
2975
0
        }
2976
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2977
0
    }
2978
2979
    // Step 1: Let the clipper infer height from first range
2980
0
    if (clipper->ItemsHeight <= 0.0f)
2981
0
    {
2982
0
        IM_ASSERT(data->StepNo == 1);
2983
0
        if (table)
2984
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2985
2986
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2987
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2988
0
        if (affected_by_floating_point_precision)
2989
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2990
2991
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2992
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2993
0
    }
2994
2995
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2996
0
    const int already_submitted = clipper->DisplayEnd;
2997
0
    if (calc_clipping)
2998
0
    {
2999
0
        if (g.LogEnabled)
3000
0
        {
3001
            // If logging is active, do not perform any clipping
3002
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3003
0
        }
3004
0
        else
3005
0
        {
3006
            // Add range selected to be included for navigation
3007
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3008
0
            if (is_nav_request)
3009
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3010
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3011
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3012
3013
            // Add focused/active item
3014
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3015
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3016
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3017
3018
            // Add visible range
3019
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3020
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3021
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3022
0
        }
3023
3024
        // Convert position ranges to item index ranges
3025
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3026
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3027
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3028
0
        for (ImGuiListClipperRange& range : data->Ranges)
3029
0
            if (range.PosToIndexConvert)
3030
0
            {
3031
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3032
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3033
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3034
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3035
0
                range.PosToIndexConvert = false;
3036
0
            }
3037
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3038
0
    }
3039
3040
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3041
0
    while (data->StepNo < data->Ranges.Size)
3042
0
    {
3043
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3044
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3045
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3046
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3047
0
        data->StepNo++;
3048
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3049
0
            continue;
3050
0
        return true;
3051
0
    }
3052
3053
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3054
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3055
0
    if (clipper->ItemsCount < INT_MAX)
3056
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3057
3058
0
    return false;
3059
0
}
3060
3061
bool ImGuiListClipper::Step()
3062
0
{
3063
0
    ImGuiContext& g = *Ctx;
3064
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3065
0
    bool ret = ImGuiListClipper_StepInternal(this);
3066
0
    if (ret && (DisplayStart == DisplayEnd))
3067
0
        ret = false;
3068
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3069
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3070
0
    if (need_items_height && ItemsHeight > 0.0f)
3071
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3072
0
    if (ret)
3073
0
    {
3074
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3075
0
    }
3076
0
    else
3077
0
    {
3078
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3079
0
        End();
3080
0
    }
3081
0
    return ret;
3082
0
}
3083
3084
//-----------------------------------------------------------------------------
3085
// [SECTION] STYLING
3086
//-----------------------------------------------------------------------------
3087
3088
ImGuiStyle& ImGui::GetStyle()
3089
70.9k
{
3090
70.9k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3091
70.9k
    return GImGui->Style;
3092
70.9k
}
3093
3094
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3095
268k
{
3096
268k
    ImGuiStyle& style = GImGui->Style;
3097
268k
    ImVec4 c = style.Colors[idx];
3098
268k
    c.w *= style.Alpha * alpha_mul;
3099
268k
    return ColorConvertFloat4ToU32(c);
3100
268k
}
3101
3102
ImU32 ImGui::GetColorU32(const ImVec4& col)
3103
0
{
3104
0
    ImGuiStyle& style = GImGui->Style;
3105
0
    ImVec4 c = col;
3106
0
    c.w *= style.Alpha;
3107
0
    return ColorConvertFloat4ToU32(c);
3108
0
}
3109
3110
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3111
0
{
3112
0
    ImGuiStyle& style = GImGui->Style;
3113
0
    return style.Colors[idx];
3114
0
}
3115
3116
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3117
0
{
3118
0
    ImGuiStyle& style = GImGui->Style;
3119
0
    alpha_mul *= style.Alpha;
3120
0
    if (alpha_mul >= 1.0f)
3121
0
        return col;
3122
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3123
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3124
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3125
0
}
3126
3127
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3128
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3129
0
{
3130
0
    ImGuiContext& g = *GImGui;
3131
0
    ImGuiColorMod backup;
3132
0
    backup.Col = idx;
3133
0
    backup.BackupValue = g.Style.Colors[idx];
3134
0
    g.ColorStack.push_back(backup);
3135
0
    if (g.DebugFlashStyleColorIdx != idx)
3136
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3137
0
}
3138
3139
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3140
22.2k
{
3141
22.2k
    ImGuiContext& g = *GImGui;
3142
22.2k
    ImGuiColorMod backup;
3143
22.2k
    backup.Col = idx;
3144
22.2k
    backup.BackupValue = g.Style.Colors[idx];
3145
22.2k
    g.ColorStack.push_back(backup);
3146
22.2k
    if (g.DebugFlashStyleColorIdx != idx)
3147
22.2k
        g.Style.Colors[idx] = col;
3148
22.2k
}
3149
3150
void ImGui::PopStyleColor(int count)
3151
22.2k
{
3152
22.2k
    ImGuiContext& g = *GImGui;
3153
22.2k
    if (g.ColorStack.Size < count)
3154
0
    {
3155
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3156
0
        count = g.ColorStack.Size;
3157
0
    }
3158
44.4k
    while (count > 0)
3159
22.2k
    {
3160
22.2k
        ImGuiColorMod& backup = g.ColorStack.back();
3161
22.2k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3162
22.2k
        g.ColorStack.pop_back();
3163
22.2k
        count--;
3164
22.2k
    }
3165
22.2k
}
3166
3167
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3168
{
3169
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3170
};
3171
3172
static const ImGuiDataVarInfo GStyleVarInfo[] =
3173
{
3174
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                 // ImGuiStyleVar_Alpha
3175
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },         // ImGuiStyleVar_DisabledAlpha
3176
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },         // ImGuiStyleVar_WindowPadding
3177
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },        // ImGuiStyleVar_WindowRounding
3178
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },      // ImGuiStyleVar_WindowBorderSize
3179
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },         // ImGuiStyleVar_WindowMinSize
3180
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },      // ImGuiStyleVar_WindowTitleAlign
3181
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },         // ImGuiStyleVar_ChildRounding
3182
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },       // ImGuiStyleVar_ChildBorderSize
3183
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },         // ImGuiStyleVar_PopupRounding
3184
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },       // ImGuiStyleVar_PopupBorderSize
3185
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },          // ImGuiStyleVar_FramePadding
3186
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },         // ImGuiStyleVar_FrameRounding
3187
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },       // ImGuiStyleVar_FrameBorderSize
3188
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },           // ImGuiStyleVar_ItemSpacing
3189
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },      // ImGuiStyleVar_ItemInnerSpacing
3190
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },         // ImGuiStyleVar_IndentSpacing
3191
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },           // ImGuiStyleVar_CellPadding
3192
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },         // ImGuiStyleVar_ScrollbarSize
3193
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },     // ImGuiStyleVar_ScrollbarRounding
3194
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },           // ImGuiStyleVar_GrabMinSize
3195
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },          // ImGuiStyleVar_GrabRounding
3196
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },           // ImGuiStyleVar_TabRounding
3197
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },         // ImGuiStyleVar_TabBorderSize
3198
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },      // ImGuiStyleVar_TabBarBorderSize
3199
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},// ImGuiStyleVar_TableAngledHeadersAngle
3200
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },       // ImGuiStyleVar_ButtonTextAlign
3201
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },   // ImGuiStyleVar_SelectableTextAlign
3202
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3203
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },    // ImGuiStyleVar_SeparatorTextAlign
3204
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },  // ImGuiStyleVar_SeparatorTextPadding
3205
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },  // ImGuiStyleVar_DockingSeparatorSize
3206
};
3207
3208
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3209
44.4k
{
3210
44.4k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3211
44.4k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3212
44.4k
    return &GStyleVarInfo[idx];
3213
44.4k
}
3214
3215
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3216
0
{
3217
0
    ImGuiContext& g = *GImGui;
3218
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3219
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3220
0
    {
3221
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3222
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3223
0
        *pvar = val;
3224
0
        return;
3225
0
    }
3226
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3227
0
}
3228
3229
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3230
22.2k
{
3231
22.2k
    ImGuiContext& g = *GImGui;
3232
22.2k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3233
22.2k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3234
22.2k
    {
3235
22.2k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3236
22.2k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3237
22.2k
        *pvar = val;
3238
22.2k
        return;
3239
22.2k
    }
3240
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3241
0
}
3242
3243
void ImGui::PopStyleVar(int count)
3244
22.2k
{
3245
22.2k
    ImGuiContext& g = *GImGui;
3246
22.2k
    if (g.StyleVarStack.Size < count)
3247
0
    {
3248
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3249
0
        count = g.StyleVarStack.Size;
3250
0
    }
3251
44.4k
    while (count > 0)
3252
22.2k
    {
3253
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3254
22.2k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3255
22.2k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3256
22.2k
        void* data = info->GetVarPtr(&g.Style);
3257
22.2k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3258
22.2k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3259
22.2k
        g.StyleVarStack.pop_back();
3260
22.2k
        count--;
3261
22.2k
    }
3262
22.2k
}
3263
3264
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3265
0
{
3266
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3267
0
    switch (idx)
3268
0
    {
3269
0
    case ImGuiCol_Text: return "Text";
3270
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3271
0
    case ImGuiCol_WindowBg: return "WindowBg";
3272
0
    case ImGuiCol_ChildBg: return "ChildBg";
3273
0
    case ImGuiCol_PopupBg: return "PopupBg";
3274
0
    case ImGuiCol_Border: return "Border";
3275
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3276
0
    case ImGuiCol_FrameBg: return "FrameBg";
3277
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3278
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3279
0
    case ImGuiCol_TitleBg: return "TitleBg";
3280
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3281
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3282
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3283
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3284
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3285
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3286
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3287
0
    case ImGuiCol_CheckMark: return "CheckMark";
3288
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3289
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3290
0
    case ImGuiCol_Button: return "Button";
3291
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3292
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3293
0
    case ImGuiCol_Header: return "Header";
3294
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3295
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3296
0
    case ImGuiCol_Separator: return "Separator";
3297
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3298
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3299
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3300
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3301
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3302
0
    case ImGuiCol_Tab: return "Tab";
3303
0
    case ImGuiCol_TabHovered: return "TabHovered";
3304
0
    case ImGuiCol_TabActive: return "TabActive";
3305
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3306
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3307
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3308
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3309
0
    case ImGuiCol_PlotLines: return "PlotLines";
3310
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3311
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3312
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3313
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3314
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3315
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3316
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3317
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3318
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3319
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3320
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3321
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3322
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3323
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3324
0
    }
3325
0
    IM_ASSERT(0);
3326
0
    return "Unknown";
3327
0
}
3328
3329
3330
//-----------------------------------------------------------------------------
3331
// [SECTION] RENDER HELPERS
3332
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3333
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3334
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3335
//-----------------------------------------------------------------------------
3336
3337
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3338
88.8k
{
3339
88.8k
    const char* text_display_end = text;
3340
88.8k
    if (!text_end)
3341
88.8k
        text_end = (const char*)-1;
3342
3343
799k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3344
710k
        text_display_end++;
3345
88.8k
    return text_display_end;
3346
88.8k
}
3347
3348
// Internal ImGui functions to render text
3349
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3350
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3351
0
{
3352
0
    ImGuiContext& g = *GImGui;
3353
0
    ImGuiWindow* window = g.CurrentWindow;
3354
3355
    // Hide anything after a '##' string
3356
0
    const char* text_display_end;
3357
0
    if (hide_text_after_hash)
3358
0
    {
3359
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3360
0
    }
3361
0
    else
3362
0
    {
3363
0
        if (!text_end)
3364
0
            text_end = text + strlen(text); // FIXME-OPT
3365
0
        text_display_end = text_end;
3366
0
    }
3367
3368
0
    if (text != text_display_end)
3369
0
    {
3370
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3371
0
        if (g.LogEnabled)
3372
0
            LogRenderedText(&pos, text, text_display_end);
3373
0
    }
3374
0
}
3375
3376
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3377
0
{
3378
0
    ImGuiContext& g = *GImGui;
3379
0
    ImGuiWindow* window = g.CurrentWindow;
3380
3381
0
    if (!text_end)
3382
0
        text_end = text + strlen(text); // FIXME-OPT
3383
3384
0
    if (text != text_end)
3385
0
    {
3386
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3387
0
        if (g.LogEnabled)
3388
0
            LogRenderedText(&pos, text, text_end);
3389
0
    }
3390
0
}
3391
3392
// Default clip_rect uses (pos_min,pos_max)
3393
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3394
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3395
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3396
// better advantage of the render function taking size into account for coarse clipping.
3397
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3398
44.4k
{
3399
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3400
44.4k
    ImVec2 pos = pos_min;
3401
44.4k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3402
3403
44.4k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3404
44.4k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3405
44.4k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3406
44.4k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3407
44.4k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3408
3409
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3410
44.4k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3411
44.4k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3412
3413
    // Render
3414
44.4k
    if (need_clipping)
3415
22.2k
    {
3416
22.2k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3417
22.2k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3418
22.2k
    }
3419
22.2k
    else
3420
22.2k
    {
3421
22.2k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3422
22.2k
    }
3423
44.4k
}
3424
3425
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3426
44.4k
{
3427
    // Hide anything after a '##' string
3428
44.4k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3429
44.4k
    const int text_len = (int)(text_display_end - text);
3430
44.4k
    if (text_len == 0)
3431
0
        return;
3432
3433
44.4k
    ImGuiContext& g = *GImGui;
3434
44.4k
    ImGuiWindow* window = g.CurrentWindow;
3435
44.4k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3436
44.4k
    if (g.LogEnabled)
3437
0
        LogRenderedText(&pos_min, text, text_display_end);
3438
44.4k
}
3439
3440
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3441
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3442
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3443
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3444
0
{
3445
0
    ImGuiContext& g = *GImGui;
3446
0
    if (text_end_full == NULL)
3447
0
        text_end_full = FindRenderedTextEnd(text);
3448
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3449
3450
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3451
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3452
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3453
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3454
0
    if (text_size.x > pos_max.x - pos_min.x)
3455
0
    {
3456
        // Hello wo...
3457
        // |       |   |
3458
        // min   max   ellipsis_max
3459
        //          <-> this is generally some padding value
3460
3461
0
        const ImFont* font = draw_list->_Data->Font;
3462
0
        const float font_size = draw_list->_Data->FontSize;
3463
0
        const float font_scale = font_size / font->FontSize;
3464
0
        const char* text_end_ellipsis = NULL;
3465
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3466
3467
        // We can now claim the space between pos_max.x and ellipsis_max.x
3468
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3469
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3470
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3471
0
        {
3472
            // Always display at least 1 character if there's no room for character + ellipsis
3473
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3474
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3475
0
        }
3476
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3477
0
        {
3478
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3479
0
            text_end_ellipsis--;
3480
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3481
0
        }
3482
3483
        // Render text, render ellipsis
3484
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3485
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3486
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3487
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3488
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3489
0
    }
3490
0
    else
3491
0
    {
3492
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3493
0
    }
3494
3495
0
    if (g.LogEnabled)
3496
0
        LogRenderedText(&pos_min, text, text_end_full);
3497
0
}
3498
3499
// Render a rectangle shaped with optional rounding and borders
3500
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3501
21.7k
{
3502
21.7k
    ImGuiContext& g = *GImGui;
3503
21.7k
    ImGuiWindow* window = g.CurrentWindow;
3504
21.7k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3505
21.7k
    const float border_size = g.Style.FrameBorderSize;
3506
21.7k
    if (border && border_size > 0.0f)
3507
21.7k
    {
3508
21.7k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3509
21.7k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3510
21.7k
    }
3511
21.7k
}
3512
3513
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3514
0
{
3515
0
    ImGuiContext& g = *GImGui;
3516
0
    ImGuiWindow* window = g.CurrentWindow;
3517
0
    const float border_size = g.Style.FrameBorderSize;
3518
0
    if (border_size > 0.0f)
3519
0
    {
3520
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3521
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3522
0
    }
3523
0
}
3524
3525
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3526
427
{
3527
427
    ImGuiContext& g = *GImGui;
3528
427
    if (id != g.NavId)
3529
383
        return;
3530
44
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3531
44
        return;
3532
0
    ImGuiWindow* window = g.CurrentWindow;
3533
0
    if (window->DC.NavHideHighlightOneFrame)
3534
0
        return;
3535
3536
0
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3537
0
    ImRect display_rect = bb;
3538
0
    display_rect.ClipWith(window->ClipRect);
3539
0
    const float thickness = 2.0f;
3540
0
    if (flags & ImGuiNavHighlightFlags_Compact)
3541
0
    {
3542
0
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3543
0
    }
3544
0
    else
3545
0
    {
3546
0
        const float distance = 3.0f + thickness * 0.5f;
3547
0
        display_rect.Expand(ImVec2(distance, distance));
3548
0
        bool fully_visible = window->ClipRect.Contains(display_rect);
3549
0
        if (!fully_visible)
3550
0
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3551
0
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3552
0
        if (!fully_visible)
3553
0
            window->DrawList->PopClipRect();
3554
0
    }
3555
0
}
3556
3557
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3558
0
{
3559
0
    ImGuiContext& g = *GImGui;
3560
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3561
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3562
0
    for (ImGuiViewportP* viewport : g.Viewports)
3563
0
    {
3564
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3565
0
        ImVec2 offset, size, uv[4];
3566
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3567
0
            continue;
3568
0
        const ImVec2 pos = base_pos - offset;
3569
0
        const float scale = base_scale * viewport->DpiScale;
3570
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3571
0
            continue;
3572
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3573
0
        ImTextureID tex_id = font_atlas->TexID;
3574
0
        draw_list->PushTextureID(tex_id);
3575
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3576
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3577
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3578
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3579
0
        draw_list->PopTextureID();
3580
0
    }
3581
0
}
3582
3583
//-----------------------------------------------------------------------------
3584
// [SECTION] INITIALIZATION, SHUTDOWN
3585
//-----------------------------------------------------------------------------
3586
3587
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3588
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3589
ImGuiContext* ImGui::GetCurrentContext()
3590
1
{
3591
1
    return GImGui;
3592
1
}
3593
3594
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3595
1
{
3596
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3597
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3598
#else
3599
1
    GImGui = ctx;
3600
1
#endif
3601
1
}
3602
3603
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3604
0
{
3605
0
    GImAllocatorAllocFunc = alloc_func;
3606
0
    GImAllocatorFreeFunc = free_func;
3607
0
    GImAllocatorUserData = user_data;
3608
0
}
3609
3610
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3611
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3612
0
{
3613
0
    *p_alloc_func = GImAllocatorAllocFunc;
3614
0
    *p_free_func = GImAllocatorFreeFunc;
3615
0
    *p_user_data = GImAllocatorUserData;
3616
0
}
3617
3618
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3619
1
{
3620
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3621
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3622
1
    SetCurrentContext(ctx);
3623
1
    Initialize();
3624
1
    if (prev_ctx != NULL)
3625
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3626
1
    return ctx;
3627
1
}
3628
3629
void ImGui::DestroyContext(ImGuiContext* ctx)
3630
0
{
3631
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3632
0
    if (ctx == NULL) //-V1051
3633
0
        ctx = prev_ctx;
3634
0
    SetCurrentContext(ctx);
3635
0
    Shutdown();
3636
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3637
0
    IM_DELETE(ctx);
3638
0
}
3639
3640
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3641
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3642
{
3643
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3644
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3645
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3646
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3647
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3648
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3649
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3650
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3651
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3652
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3653
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3654
};
3655
3656
void ImGui::Initialize()
3657
1
{
3658
1
    ImGuiContext& g = *GImGui;
3659
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3660
3661
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3662
1
    {
3663
1
        ImGuiSettingsHandler ini_handler;
3664
1
        ini_handler.TypeName = "Window";
3665
1
        ini_handler.TypeHash = ImHashStr("Window");
3666
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3667
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3668
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3669
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3670
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3671
1
        AddSettingsHandler(&ini_handler);
3672
1
    }
3673
1
    TableSettingsAddSettingsHandler();
3674
3675
    // Setup default localization table
3676
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3677
3678
    // Setup default platform clipboard/IME handlers.
3679
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3680
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3681
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3682
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3683
3684
    // Create default viewport
3685
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3686
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3687
1
    viewport->Idx = 0;
3688
1
    viewport->PlatformWindowCreated = true;
3689
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3690
1
    g.Viewports.push_back(viewport);
3691
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3692
1
    g.ViewportCreatedCount++;
3693
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3694
3695
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3696
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3697
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3698
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3699
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3700
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3701
64
            g.KeysMayBeCharInput.SetBit(key);
3702
3703
1
#ifdef IMGUI_HAS_DOCK
3704
    // Initialize Docking
3705
1
    DockContextInitialize(&g);
3706
1
#endif
3707
3708
1
    g.Initialized = true;
3709
1
}
3710
3711
// This function is merely here to free heap allocations.
3712
void ImGui::Shutdown()
3713
0
{
3714
0
    ImGuiContext& g = *GImGui;
3715
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3716
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3717
3718
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3719
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3720
0
    {
3721
0
        g.IO.Fonts->Locked = false;
3722
0
        IM_DELETE(g.IO.Fonts);
3723
0
    }
3724
0
    g.IO.Fonts = NULL;
3725
0
    g.DrawListSharedData.TempBuffer.clear();
3726
3727
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3728
0
    if (!g.Initialized)
3729
0
        return;
3730
3731
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3732
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3733
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3734
3735
    // Destroy platform windows
3736
0
    DestroyPlatformWindows();
3737
3738
    // Shutdown extensions
3739
0
    DockContextShutdown(&g);
3740
3741
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3742
3743
    // Clear everything else
3744
0
    g.Windows.clear_delete();
3745
0
    g.WindowsFocusOrder.clear();
3746
0
    g.WindowsTempSortBuffer.clear();
3747
0
    g.CurrentWindow = NULL;
3748
0
    g.CurrentWindowStack.clear();
3749
0
    g.WindowsById.Clear();
3750
0
    g.NavWindow = NULL;
3751
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3752
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3753
0
    g.MovingWindow = NULL;
3754
3755
0
    g.KeysRoutingTable.Clear();
3756
3757
0
    g.ColorStack.clear();
3758
0
    g.StyleVarStack.clear();
3759
0
    g.FontStack.clear();
3760
0
    g.OpenPopupStack.clear();
3761
0
    g.BeginPopupStack.clear();
3762
0
    g.NavTreeNodeStack.clear();
3763
3764
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3765
0
    g.Viewports.clear_delete();
3766
3767
0
    g.TabBars.Clear();
3768
0
    g.CurrentTabBarStack.clear();
3769
0
    g.ShrinkWidthBuffer.clear();
3770
3771
0
    g.ClipperTempData.clear_destruct();
3772
3773
0
    g.Tables.Clear();
3774
0
    g.TablesTempData.clear_destruct();
3775
0
    g.DrawChannelsTempMergeBuffer.clear();
3776
3777
0
    g.ClipboardHandlerData.clear();
3778
0
    g.MenusIdSubmittedThisFrame.clear();
3779
0
    g.InputTextState.ClearFreeMemory();
3780
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3781
3782
0
    g.SettingsWindows.clear();
3783
0
    g.SettingsHandlers.clear();
3784
3785
0
    if (g.LogFile)
3786
0
    {
3787
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3788
0
        if (g.LogFile != stdout)
3789
0
#endif
3790
0
            ImFileClose(g.LogFile);
3791
0
        g.LogFile = NULL;
3792
0
    }
3793
0
    g.LogBuffer.clear();
3794
0
    g.DebugLogBuf.clear();
3795
0
    g.DebugLogIndex.clear();
3796
3797
0
    g.Initialized = false;
3798
0
}
3799
3800
// No specific ordering/dependency support, will see as needed
3801
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3802
0
{
3803
0
    ImGuiContext& g = *ctx;
3804
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3805
0
    g.Hooks.push_back(*hook);
3806
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3807
0
    return g.HookIdNext;
3808
0
}
3809
3810
// Deferred removal, avoiding issue with changing vector while iterating it
3811
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3812
0
{
3813
0
    ImGuiContext& g = *ctx;
3814
0
    IM_ASSERT(hook_id != 0);
3815
0
    for (ImGuiContextHook& hook : g.Hooks)
3816
0
        if (hook.HookId == hook_id)
3817
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3818
0
}
3819
3820
// Call context hooks (used by e.g. test engine)
3821
// We assume a small number of hooks so all stored in same array
3822
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3823
133k
{
3824
133k
    ImGuiContext& g = *ctx;
3825
133k
    for (ImGuiContextHook& hook : g.Hooks)
3826
0
        if (hook.Type == hook_type)
3827
0
            hook.Callback(&g, &hook);
3828
133k
}
3829
3830
3831
//-----------------------------------------------------------------------------
3832
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3833
//-----------------------------------------------------------------------------
3834
3835
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3836
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3837
3
{
3838
3
    memset(this, 0, sizeof(*this));
3839
3
    Ctx = ctx;
3840
3
    Name = ImStrdup(name);
3841
3
    NameBufLen = (int)strlen(name) + 1;
3842
3
    ID = ImHashStr(name);
3843
3
    IDStack.push_back(ID);
3844
3
    ViewportAllowPlatformMonitorExtend = -1;
3845
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3846
3
    MoveId = GetID("#MOVE");
3847
3
    TabId = GetID("#TAB");
3848
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3849
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3850
3
    AutoFitFramesX = AutoFitFramesY = -1;
3851
3
    AutoPosLastDirection = ImGuiDir_None;
3852
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3853
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3854
3
    LastFrameActive = -1;
3855
3
    LastFrameJustFocused = -1;
3856
3
    LastTimeActive = -1.0f;
3857
3
    FontWindowScale = FontDpiScale = 1.0f;
3858
3
    SettingsOffset = -1;
3859
3
    DockOrder = -1;
3860
3
    DrawList = &DrawListInst;
3861
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3862
3
    DrawList->_OwnerName = Name;
3863
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3864
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3865
3
}
3866
3867
ImGuiWindow::~ImGuiWindow()
3868
0
{
3869
0
    IM_ASSERT(DrawList == &DrawListInst);
3870
0
    IM_DELETE(Name);
3871
0
    ColumnsStorage.clear_destruct();
3872
0
}
3873
3874
static void SetCurrentWindow(ImGuiWindow* window)
3875
89.7k
{
3876
89.7k
    ImGuiContext& g = *GImGui;
3877
89.7k
    g.CurrentWindow = window;
3878
89.7k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3879
89.7k
    if (window)
3880
67.4k
    {
3881
67.4k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3882
67.4k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3883
67.4k
    }
3884
89.7k
}
3885
3886
void ImGui::GcCompactTransientMiscBuffers()
3887
0
{
3888
0
    ImGuiContext& g = *GImGui;
3889
0
    g.ItemFlagsStack.clear();
3890
0
    g.GroupStack.clear();
3891
0
    TableGcCompactSettings();
3892
0
}
3893
3894
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3895
// Not freed:
3896
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3897
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3898
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3899
1
{
3900
1
    window->MemoryCompacted = true;
3901
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3902
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3903
1
    window->IDStack.clear();
3904
1
    window->DrawList->_ClearFreeMemory();
3905
1
    window->DC.ChildWindows.clear();
3906
1
    window->DC.ItemWidthStack.clear();
3907
1
    window->DC.TextWrapPosStack.clear();
3908
1
}
3909
3910
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3911
0
{
3912
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3913
    // The other buffers tends to amortize much faster.
3914
0
    window->MemoryCompacted = false;
3915
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3916
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3917
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3918
0
}
3919
3920
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3921
68
{
3922
68
    ImGuiContext& g = *GImGui;
3923
3924
    // Clear previous active id
3925
68
    if (g.ActiveId != 0)
3926
34
    {
3927
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3928
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3929
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3930
34
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3931
0
        {
3932
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3933
0
            g.MovingWindow = NULL;
3934
0
        }
3935
3936
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3937
        // but since this is currently quite an exception we'll leave it as is.
3938
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3939
34
        if (g.InputTextState.ID == g.ActiveId)
3940
0
            InputTextDeactivateHook(g.ActiveId);
3941
34
    }
3942
3943
    // Set active id
3944
68
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3945
68
    if (g.ActiveIdIsJustActivated)
3946
68
    {
3947
68
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3948
68
        g.ActiveIdTimer = 0.0f;
3949
68
        g.ActiveIdHasBeenPressedBefore = false;
3950
68
        g.ActiveIdHasBeenEditedBefore = false;
3951
68
        g.ActiveIdMouseButton = -1;
3952
68
        if (id != 0)
3953
34
        {
3954
34
            g.LastActiveId = id;
3955
34
            g.LastActiveIdTimer = 0.0f;
3956
34
        }
3957
68
    }
3958
68
    g.ActiveId = id;
3959
68
    g.ActiveIdAllowOverlap = false;
3960
68
    g.ActiveIdNoClearOnFocusLoss = false;
3961
68
    g.ActiveIdWindow = window;
3962
68
    g.ActiveIdHasBeenEditedThisFrame = false;
3963
68
    g.ActiveIdFromShortcut = false;
3964
68
    if (id)
3965
34
    {
3966
34
        g.ActiveIdIsAlive = id;
3967
34
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3968
34
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3969
34
    }
3970
3971
    // Clear declaration of inputs claimed by the widget
3972
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3973
68
    g.ActiveIdUsingNavDirMask = 0x00;
3974
68
    g.ActiveIdUsingAllKeyboardKeys = false;
3975
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3976
    g.ActiveIdUsingNavInputMask = 0x00;
3977
#endif
3978
68
}
3979
3980
void ImGui::ClearActiveID()
3981
34
{
3982
34
    SetActiveID(0, NULL); // g.ActiveId = 0;
3983
34
}
3984
3985
void ImGui::SetHoveredID(ImGuiID id)
3986
42
{
3987
42
    ImGuiContext& g = *GImGui;
3988
42
    g.HoveredId = id;
3989
42
    g.HoveredIdAllowOverlap = false;
3990
42
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3991
23
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3992
42
}
3993
3994
ImGuiID ImGui::GetHoveredID()
3995
0
{
3996
0
    ImGuiContext& g = *GImGui;
3997
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3998
0
}
3999
4000
void ImGui::MarkItemEdited(ImGuiID id)
4001
0
{
4002
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4003
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4004
0
    ImGuiContext& g = *GImGui;
4005
0
    if (g.LockMarkEdited > 0)
4006
0
        return;
4007
0
    if (g.ActiveId == id || g.ActiveId == 0)
4008
0
    {
4009
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4010
0
        g.ActiveIdHasBeenEditedBefore = true;
4011
0
    }
4012
4013
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4014
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4015
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4016
4017
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4018
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4019
0
}
4020
4021
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4022
43
{
4023
    // An active popup disable hovering on other windows (apart from its own children)
4024
    // FIXME-OPT: This could be cached/stored within the window.
4025
43
    ImGuiContext& g = *GImGui;
4026
43
    if (g.NavWindow)
4027
0
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4028
0
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4029
0
            {
4030
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4031
                // NB: The 'else' is important because Modal windows are also Popups.
4032
0
                bool want_inhibit = false;
4033
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4034
0
                    want_inhibit = true;
4035
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4036
0
                    want_inhibit = true;
4037
4038
                // Inhibit hover unless the window is within the stack of our modal/popup
4039
0
                if (want_inhibit)
4040
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4041
0
                        return false;
4042
0
            }
4043
4044
    // Filter by viewport
4045
43
    if (window->Viewport != g.MouseViewport)
4046
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4047
0
            return false;
4048
4049
43
    return true;
4050
43
}
4051
4052
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4053
0
{
4054
0
    ImGuiContext& g = *GImGui;
4055
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4056
0
        return g.Style.HoverDelayNormal;
4057
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4058
0
        return g.Style.HoverDelayShort;
4059
0
    return 0.0f;
4060
0
}
4061
4062
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4063
0
{
4064
    // Allow instance flags to override shared flags
4065
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4066
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4067
0
    return user_flags | shared_flags;
4068
0
}
4069
4070
// This is roughly matching the behavior of internal-facing ItemHoverable()
4071
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4072
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4073
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4074
0
{
4075
0
    ImGuiContext& g = *GImGui;
4076
0
    ImGuiWindow* window = g.CurrentWindow;
4077
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4078
4079
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4080
0
    {
4081
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4082
0
            return false;
4083
0
        if (!IsItemFocused())
4084
0
            return false;
4085
4086
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4087
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4088
0
    }
4089
0
    else
4090
0
    {
4091
        // Test for bounding box overlap, as updated as ItemAdd()
4092
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4093
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4094
0
            return false;
4095
4096
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4097
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4098
4099
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4100
4101
        // Done with rectangle culling so we can perform heavier checks now
4102
        // Test if we are hovering the right window (our window could be behind another window)
4103
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4104
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4105
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4106
        // the test that has been running for a long while.
4107
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4108
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4109
0
                return false;
4110
4111
        // Test if another item is active (e.g. being dragged)
4112
0
        const ImGuiID id = g.LastItemData.ID;
4113
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4114
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4115
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4116
0
                    return false;
4117
4118
        // Test if interactions on this window are blocked by an active popup or modal.
4119
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4120
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4121
0
            return false;
4122
4123
        // Test if the item is disabled
4124
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4125
0
            return false;
4126
4127
        // Special handling for calling after Begin() which represent the title bar or tab.
4128
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4129
        // will never be overwritten so we need to detect the case.
4130
0
        if (id == window->MoveId && window->WriteAccessed)
4131
0
            return false;
4132
4133
        // Test if using AllowOverlap and overlapped
4134
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4135
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4136
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4137
0
                    return false;
4138
0
    }
4139
4140
    // Handle hover delay
4141
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4142
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4143
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4144
0
    {
4145
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4146
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4147
0
            g.HoverItemDelayTimer = 0.0f;
4148
0
        g.HoverItemDelayId = hover_delay_id;
4149
4150
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4151
        // but once unlocked on a given item we also moving.
4152
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4153
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4154
0
            return false;
4155
4156
0
        if (g.HoverItemDelayTimer < delay)
4157
0
            return false;
4158
0
    }
4159
4160
0
    return true;
4161
0
}
4162
4163
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4164
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4165
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4166
// If you used this in your legacy/custom widgets code:
4167
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4168
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4169
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4170
45.1k
{
4171
45.1k
    ImGuiContext& g = *GImGui;
4172
45.1k
    ImGuiWindow* window = g.CurrentWindow;
4173
45.1k
    if (g.HoveredWindow != window)
4174
43.9k
        return false;
4175
1.17k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4176
1.13k
        return false;
4177
4178
42
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4179
0
        return false;
4180
42
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4181
0
        if (!g.ActiveIdFromShortcut)
4182
0
            return false;
4183
4184
    // Done with rectangle culling so we can perform heavier checks now.
4185
42
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4186
0
    {
4187
0
        g.HoveredIdDisabled = true;
4188
0
        return false;
4189
0
    }
4190
4191
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4192
    // hover test in widgets code. We could also decide to split this function is two.
4193
42
    if (id != 0)
4194
42
    {
4195
        // Drag source doesn't report as hovered
4196
42
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4197
0
            return false;
4198
4199
42
        SetHoveredID(id);
4200
4201
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4202
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4203
42
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4204
0
        {
4205
0
            g.HoveredIdAllowOverlap = true;
4206
0
            if (g.HoveredIdPreviousFrame != id)
4207
0
                return false;
4208
0
        }
4209
42
    }
4210
4211
    // When disabled we'll return false but still set HoveredId
4212
42
    if (item_flags & ImGuiItemFlags_Disabled)
4213
0
    {
4214
        // Release active id if turning disabled
4215
0
        if (g.ActiveId == id && id != 0)
4216
0
            ClearActiveID();
4217
0
        g.HoveredIdDisabled = true;
4218
0
        return false;
4219
0
    }
4220
4221
42
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4222
42
    if (id != 0)
4223
42
    {
4224
        // [DEBUG] Item Picker tool!
4225
        // We perform the check here because reaching is path is rare (1~ time a frame),
4226
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4227
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4228
42
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4229
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4230
42
        if (g.DebugItemPickerBreakId == id)
4231
0
            IM_DEBUG_BREAK();
4232
42
    }
4233
42
#endif
4234
4235
42
    if (g.NavDisableMouseHover)
4236
0
        return false;
4237
4238
42
    return true;
4239
42
}
4240
4241
// FIXME: This is inlined/duplicated in ItemAdd()
4242
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4243
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4244
0
{
4245
0
    ImGuiContext& g = *GImGui;
4246
0
    ImGuiWindow* window = g.CurrentWindow;
4247
0
    if (!bb.Overlaps(window->ClipRect))
4248
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4249
0
            if (!g.LogEnabled)
4250
0
                return true;
4251
0
    return false;
4252
0
}
4253
4254
// This is also inlined in ItemAdd()
4255
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4256
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4257
44.8k
{
4258
44.8k
    ImGuiContext& g = *GImGui;
4259
44.8k
    g.LastItemData.ID = item_id;
4260
44.8k
    g.LastItemData.InFlags = in_flags;
4261
44.8k
    g.LastItemData.StatusFlags = item_flags;
4262
44.8k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4263
44.8k
}
4264
4265
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4266
0
{
4267
0
    if (wrap_pos_x < 0.0f)
4268
0
        return 0.0f;
4269
4270
0
    ImGuiContext& g = *GImGui;
4271
0
    ImGuiWindow* window = g.CurrentWindow;
4272
0
    if (wrap_pos_x == 0.0f)
4273
0
    {
4274
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4275
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4276
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4277
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4278
        //else
4279
0
        wrap_pos_x = window->WorkRect.Max.x;
4280
0
    }
4281
0
    else if (wrap_pos_x > 0.0f)
4282
0
    {
4283
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4284
0
    }
4285
4286
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4287
0
}
4288
4289
// IM_ALLOC() == ImGui::MemAlloc()
4290
void* ImGui::MemAlloc(size_t size)
4291
1.19k
{
4292
1.19k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4293
1.19k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4294
1.19k
    if (ImGuiContext* ctx = GImGui)
4295
1.19k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4296
1.19k
#endif
4297
1.19k
    return ptr;
4298
1.19k
}
4299
4300
// IM_FREE() == ImGui::MemFree()
4301
void ImGui::MemFree(void* ptr)
4302
1.15k
{
4303
1.15k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4304
1.15k
    if (ptr != NULL)
4305
1.14k
        if (ImGuiContext* ctx = GImGui)
4306
1.14k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4307
1.15k
#endif
4308
1.15k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4309
1.15k
}
4310
4311
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4312
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4313
2.34k
{
4314
2.34k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4315
2.34k
    IM_UNUSED(ptr);
4316
2.34k
    if (entry->FrameCount != frame_count)
4317
24
    {
4318
24
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4319
24
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4320
24
        entry->FrameCount = frame_count;
4321
24
        entry->AllocCount = entry->FreeCount = 0;
4322
24
    }
4323
2.34k
    if (size != (size_t)-1)
4324
1.19k
    {
4325
1.19k
        entry->AllocCount++;
4326
1.19k
        info->TotalAllocCount++;
4327
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4328
1.19k
    }
4329
1.14k
    else
4330
1.14k
    {
4331
1.14k
        entry->FreeCount++;
4332
1.14k
        info->TotalFreeCount++;
4333
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4334
1.14k
    }
4335
2.34k
}
4336
4337
const char* ImGui::GetClipboardText()
4338
0
{
4339
0
    ImGuiContext& g = *GImGui;
4340
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4341
0
}
4342
4343
void ImGui::SetClipboardText(const char* text)
4344
0
{
4345
0
    ImGuiContext& g = *GImGui;
4346
0
    if (g.IO.SetClipboardTextFn)
4347
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4348
0
}
4349
4350
const char* ImGui::GetVersion()
4351
0
{
4352
0
    return IMGUI_VERSION;
4353
0
}
4354
4355
ImGuiIO& ImGui::GetIO()
4356
70.3k
{
4357
70.3k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4358
70.3k
    return GImGui->IO;
4359
70.3k
}
4360
4361
ImGuiPlatformIO& ImGui::GetPlatformIO()
4362
0
{
4363
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4364
0
    return GImGui->PlatformIO;
4365
0
}
4366
4367
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4368
ImDrawData* ImGui::GetDrawData()
4369
22.2k
{
4370
22.2k
    ImGuiContext& g = *GImGui;
4371
22.2k
    ImGuiViewportP* viewport = g.Viewports[0];
4372
22.2k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4373
22.2k
}
4374
4375
double ImGui::GetTime()
4376
1
{
4377
1
    return GImGui->Time;
4378
1
}
4379
4380
int ImGui::GetFrameCount()
4381
0
{
4382
0
    return GImGui->FrameCount;
4383
0
}
4384
4385
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4386
0
{
4387
    // Create the draw list on demand, because they are not frequently used for all viewports
4388
0
    ImGuiContext& g = *GImGui;
4389
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4390
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4391
0
    if (draw_list == NULL)
4392
0
    {
4393
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4394
0
        draw_list->_OwnerName = drawlist_name;
4395
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4396
0
    }
4397
4398
    // Our ImDrawList system requires that there is always a command
4399
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4400
0
    {
4401
0
        draw_list->_ResetForNewFrame();
4402
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4403
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4404
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4405
0
    }
4406
0
    return draw_list;
4407
0
}
4408
4409
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4410
0
{
4411
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4412
0
}
4413
4414
ImDrawList* ImGui::GetBackgroundDrawList()
4415
0
{
4416
0
    ImGuiContext& g = *GImGui;
4417
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4418
0
}
4419
4420
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4421
0
{
4422
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4423
0
}
4424
4425
ImDrawList* ImGui::GetForegroundDrawList()
4426
0
{
4427
0
    ImGuiContext& g = *GImGui;
4428
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4429
0
}
4430
4431
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4432
0
{
4433
0
    return &GImGui->DrawListSharedData;
4434
0
}
4435
4436
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4437
16
{
4438
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4439
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4440
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4441
16
    ImGuiContext& g = *GImGui;
4442
16
    FocusWindow(window);
4443
16
    SetActiveID(window->MoveId, window);
4444
16
    g.NavDisableHighlight = true;
4445
16
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4446
16
    g.ActiveIdNoClearOnFocusLoss = true;
4447
16
    SetActiveIdUsingAllKeyboardKeys();
4448
4449
16
    bool can_move_window = true;
4450
16
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4451
0
        can_move_window = false;
4452
16
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4453
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4454
0
            can_move_window = false;
4455
16
    if (can_move_window)
4456
16
        g.MovingWindow = window;
4457
16
}
4458
4459
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4460
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4461
0
{
4462
0
    ImGuiContext& g = *GImGui;
4463
0
    bool can_undock_node = false;
4464
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4465
0
    {
4466
        // Can undock if:
4467
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4468
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4469
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4470
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4471
0
            can_undock_node = true;
4472
0
    }
4473
4474
0
    const bool clicked = IsMouseClicked(0);
4475
0
    const bool dragging = IsMouseDragging(0);
4476
0
    if (can_undock_node && dragging)
4477
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4478
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4479
0
        StartMouseMovingWindow(window);
4480
0
}
4481
4482
// Handle mouse moving window
4483
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4484
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4485
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4486
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4487
void ImGui::UpdateMouseMovingWindowNewFrame()
4488
22.2k
{
4489
22.2k
    ImGuiContext& g = *GImGui;
4490
22.2k
    if (g.MovingWindow != NULL)
4491
22
    {
4492
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4493
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4494
22
        KeepAliveID(g.ActiveId);
4495
22
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4496
22
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4497
4498
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4499
22
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4500
22
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4501
6
        {
4502
6
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4503
6
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4504
1
            {
4505
1
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4506
1
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4507
0
                {
4508
0
                    moving_window->Viewport->Pos = pos;
4509
0
                    moving_window->Viewport->UpdateWorkRect();
4510
0
                }
4511
1
            }
4512
6
            FocusWindow(g.MovingWindow);
4513
6
        }
4514
16
        else
4515
16
        {
4516
16
            if (!window_disappared)
4517
16
            {
4518
                // Try to merge the window back into the main viewport.
4519
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4520
16
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4521
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4522
4523
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4524
16
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4525
16
                    g.MouseViewport = moving_window->Viewport;
4526
4527
                // Clear the NoInput window flag set by the Viewport system
4528
16
                if (moving_window->Viewport)
4529
16
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4530
16
            }
4531
4532
16
            g.MovingWindow = NULL;
4533
16
            ClearActiveID();
4534
16
        }
4535
22
    }
4536
22.1k
    else
4537
22.1k
    {
4538
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4539
22.1k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4540
0
        {
4541
0
            KeepAliveID(g.ActiveId);
4542
0
            if (!g.IO.MouseDown[0])
4543
0
                ClearActiveID();
4544
0
        }
4545
22.1k
    }
4546
22.2k
}
4547
4548
// Initiate moving window when clicking on empty space or title bar.
4549
// Handle left-click and right-click focus.
4550
void ImGui::UpdateMouseMovingWindowEndFrame()
4551
22.2k
{
4552
22.2k
    ImGuiContext& g = *GImGui;
4553
22.2k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4554
48
        return;
4555
4556
    // Unless we just made a window/popup appear
4557
22.1k
    if (g.NavWindow && g.NavWindow->Appearing)
4558
1
        return;
4559
4560
    // Click on empty space to focus window and start moving
4561
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4562
22.1k
    if (g.IO.MouseClicked[0])
4563
929
    {
4564
        // Handle the edge case of a popup being closed while clicking in its empty space.
4565
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4566
929
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4567
929
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4568
4569
929
        if (root_window != NULL && !is_closed_popup)
4570
16
        {
4571
16
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4572
4573
            // Cancel moving if clicked outside of title bar
4574
16
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4575
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4576
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4577
0
                        g.MovingWindow = NULL;
4578
4579
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4580
16
            if (g.HoveredIdDisabled)
4581
0
                g.MovingWindow = NULL;
4582
16
        }
4583
913
        else if (root_window == NULL && g.NavWindow != NULL)
4584
0
        {
4585
            // Clicking on void disable focus
4586
0
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4587
0
        }
4588
929
    }
4589
4590
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4591
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4592
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4593
22.1k
    if (g.IO.MouseClicked[1])
4594
171
    {
4595
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4596
        // This is where we can trim the popup stack.
4597
171
        ImGuiWindow* modal = GetTopMostPopupModal();
4598
171
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4599
171
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4600
171
    }
4601
22.1k
}
4602
4603
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4604
// Need to keep in sync with SetWindowPos()
4605
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4606
0
{
4607
0
    window->Pos += delta;
4608
0
    window->ClipRect.Translate(delta);
4609
0
    window->OuterRectClipped.Translate(delta);
4610
0
    window->InnerRect.Translate(delta);
4611
0
    window->DC.CursorPos += delta;
4612
0
    window->DC.CursorStartPos += delta;
4613
0
    window->DC.CursorMaxPos += delta;
4614
0
    window->DC.IdealMaxPos += delta;
4615
0
}
4616
4617
static void ScaleWindow(ImGuiWindow* window, float scale)
4618
0
{
4619
0
    ImVec2 origin = window->Viewport->Pos;
4620
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4621
0
    window->Size = ImTrunc(window->Size * scale);
4622
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4623
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4624
0
}
4625
4626
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4627
67.0k
{
4628
67.0k
    return (window->Active) && (!window->Hidden);
4629
67.0k
}
4630
4631
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4632
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4633
22.2k
{
4634
22.2k
    ImGuiContext& g = *GImGui;
4635
22.2k
    ImGuiIO& io = g.IO;
4636
22.2k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4637
4638
    // Find the window hovered by mouse:
4639
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4640
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4641
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4642
22.2k
    bool clear_hovered_windows = false;
4643
22.2k
    FindHoveredWindow();
4644
22.2k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4645
4646
    // Modal windows prevents mouse from hovering behind them.
4647
22.2k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4648
22.2k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4649
0
        clear_hovered_windows = true;
4650
4651
    // Disabled mouse?
4652
22.2k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4653
0
        clear_hovered_windows = true;
4654
4655
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4656
    // won't report hovering nor request capture even while dragging over our windows afterward.
4657
22.2k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4658
22.2k
    const bool has_open_modal = (modal_window != NULL);
4659
22.2k
    int mouse_earliest_down = -1;
4660
22.2k
    bool mouse_any_down = false;
4661
133k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4662
111k
    {
4663
111k
        if (io.MouseClicked[i])
4664
1.75k
        {
4665
1.75k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4666
1.75k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4667
1.75k
        }
4668
111k
        mouse_any_down |= io.MouseDown[i];
4669
111k
        if (io.MouseDown[i])
4670
6.82k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4671
4.60k
                mouse_earliest_down = i;
4672
111k
    }
4673
22.2k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4674
22.2k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4675
4676
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4677
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4678
22.2k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4679
22.2k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4680
4.01k
        clear_hovered_windows = true;
4681
4682
22.2k
    if (clear_hovered_windows)
4683
4.01k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4684
4685
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4686
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4687
22.2k
    if (g.WantCaptureMouseNextFrame != -1)
4688
0
    {
4689
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4690
0
    }
4691
22.2k
    else
4692
22.2k
    {
4693
22.2k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4694
22.2k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4695
22.2k
    }
4696
4697
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4698
22.2k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4699
22.2k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4700
6
        io.WantCaptureKeyboard = true;
4701
22.2k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4702
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4703
4704
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4705
22.2k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4706
22.2k
}
4707
4708
void ImGui::NewFrame()
4709
22.2k
{
4710
22.2k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4711
22.2k
    ImGuiContext& g = *GImGui;
4712
4713
    // Remove pending delete hooks before frame start.
4714
    // This deferred removal avoid issues of removal while iterating the hook vector
4715
22.2k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4716
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4717
0
            g.Hooks.erase(&g.Hooks[n]);
4718
4719
22.2k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4720
4721
    // Check and assert for various common IO and Configuration mistakes
4722
22.2k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4723
22.2k
    ErrorCheckNewFrameSanityChecks();
4724
22.2k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4725
4726
    // Load settings on first frame, save settings when modified (after a delay)
4727
22.2k
    UpdateSettings();
4728
4729
22.2k
    g.Time += g.IO.DeltaTime;
4730
22.2k
    g.WithinFrameScope = true;
4731
22.2k
    g.FrameCount += 1;
4732
22.2k
    g.TooltipOverrideCount = 0;
4733
22.2k
    g.WindowsActiveCount = 0;
4734
22.2k
    g.MenusIdSubmittedThisFrame.resize(0);
4735
4736
    // Calculate frame-rate for the user, as a purely luxurious feature
4737
22.2k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4738
22.2k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4739
22.2k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4740
22.2k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4741
22.2k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4742
4743
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4744
22.2k
    g.InputEventsTrail.resize(0);
4745
22.2k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4746
4747
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4748
22.2k
    UpdateViewportsNewFrame();
4749
4750
    // Setup current font and draw list shared data
4751
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4752
22.2k
    g.IO.Fonts->Locked = true;
4753
22.2k
    SetCurrentFont(GetDefaultFont());
4754
22.2k
    IM_ASSERT(g.Font->IsLoaded());
4755
22.2k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4756
22.2k
    for (ImGuiViewportP* viewport : g.Viewports)
4757
22.2k
        virtual_space.Add(viewport->GetMainRect());
4758
22.2k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4759
22.2k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4760
22.2k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4761
22.2k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4762
22.2k
    if (g.Style.AntiAliasedLines)
4763
22.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4764
22.2k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4765
22.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4766
22.2k
    if (g.Style.AntiAliasedFill)
4767
22.2k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4768
22.2k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4769
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4770
4771
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4772
22.2k
    for (ImGuiViewportP* viewport : g.Viewports)
4773
22.2k
    {
4774
22.2k
        viewport->DrawData = NULL;
4775
22.2k
        viewport->DrawDataP.Valid = false;
4776
22.2k
    }
4777
4778
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4779
22.2k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4780
0
        KeepAliveID(g.DragDropPayload.SourceId);
4781
4782
    // Update HoveredId data
4783
22.2k
    if (!g.HoveredIdPreviousFrame)
4784
22.1k
        g.HoveredIdTimer = 0.0f;
4785
22.2k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4786
22.1k
        g.HoveredIdNotActiveTimer = 0.0f;
4787
22.2k
    if (g.HoveredId)
4788
42
        g.HoveredIdTimer += g.IO.DeltaTime;
4789
22.2k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4790
42
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4791
22.2k
    g.HoveredIdPreviousFrame = g.HoveredId;
4792
22.2k
    g.HoveredId = 0;
4793
22.2k
    g.HoveredIdAllowOverlap = false;
4794
22.2k
    g.HoveredIdDisabled = false;
4795
4796
    // Clear ActiveID if the item is not alive anymore.
4797
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4798
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4799
22.2k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4800
0
    {
4801
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4802
0
        ClearActiveID();
4803
0
    }
4804
4805
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4806
22.2k
    if (g.ActiveId)
4807
22
        g.ActiveIdTimer += g.IO.DeltaTime;
4808
22.2k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4809
22.2k
    g.ActiveIdPreviousFrame = g.ActiveId;
4810
22.2k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4811
22.2k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4812
22.2k
    g.ActiveIdIsAlive = 0;
4813
22.2k
    g.ActiveIdHasBeenEditedThisFrame = false;
4814
22.2k
    g.ActiveIdPreviousFrameIsAlive = false;
4815
22.2k
    g.ActiveIdIsJustActivated = false;
4816
22.2k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4817
0
        g.TempInputId = 0;
4818
22.2k
    if (g.ActiveId == 0)
4819
22.1k
    {
4820
22.1k
        g.ActiveIdUsingNavDirMask = 0x00;
4821
22.1k
        g.ActiveIdUsingAllKeyboardKeys = false;
4822
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4823
        g.ActiveIdUsingNavInputMask = 0x00;
4824
#endif
4825
22.1k
    }
4826
4827
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4828
    if (g.ActiveId == 0)
4829
        g.ActiveIdUsingNavInputMask = 0;
4830
    else if (g.ActiveIdUsingNavInputMask != 0)
4831
    {
4832
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4833
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4834
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4835
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4836
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4837
            IM_ASSERT(0); // Other values unsupported
4838
    }
4839
#endif
4840
4841
    // Record when we have been stationary as this state is preserved while over same item.
4842
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4843
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4844
22.2k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4845
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4846
22.2k
    else if (g.HoverItemDelayId == 0)
4847
22.2k
        g.HoverItemUnlockedStationaryId = 0;
4848
22.2k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4849
656
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4850
21.5k
    else if (g.HoveredWindow == NULL)
4851
21.0k
        g.HoverWindowUnlockedStationaryId = 0;
4852
4853
    // Update hover delay for IsItemHovered() with delays and tooltips
4854
22.2k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4855
22.2k
    if (g.HoverItemDelayId != 0)
4856
0
    {
4857
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4858
0
        g.HoverItemDelayClearTimer = 0.0f;
4859
0
        g.HoverItemDelayId = 0;
4860
0
    }
4861
22.2k
    else if (g.HoverItemDelayTimer > 0.0f)
4862
0
    {
4863
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4864
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4865
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4866
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4867
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4868
0
    }
4869
4870
    // Drag and drop
4871
22.2k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4872
22.2k
    g.DragDropAcceptIdCurr = 0;
4873
22.2k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4874
22.2k
    g.DragDropWithinSource = false;
4875
22.2k
    g.DragDropWithinTarget = false;
4876
22.2k
    g.DragDropHoldJustPressedId = 0;
4877
4878
    // Close popups on focus lost (currently wip/opt-in)
4879
    //if (g.IO.AppFocusLost)
4880
    //    ClosePopupsExceptModals();
4881
4882
    // Update keyboard input state
4883
22.2k
    UpdateKeyboardInputs();
4884
4885
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4886
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4887
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4888
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4889
4890
    // Update gamepad/keyboard navigation
4891
22.2k
    NavUpdate();
4892
4893
    // Update mouse input state
4894
22.2k
    UpdateMouseInputs();
4895
4896
    // Undocking
4897
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4898
22.2k
    DockContextNewFrameUpdateUndocking(&g);
4899
4900
    // Find hovered window
4901
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4902
22.2k
    UpdateHoveredWindowAndCaptureFlags();
4903
4904
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4905
22.2k
    UpdateMouseMovingWindowNewFrame();
4906
4907
    // Background darkening/whitening
4908
22.2k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4909
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4910
22.2k
    else
4911
22.2k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4912
4913
22.2k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4914
22.2k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4915
4916
    // Platform IME data: reset for the frame
4917
22.2k
    g.PlatformImeDataPrev = g.PlatformImeData;
4918
22.2k
    g.PlatformImeData.WantVisible = false;
4919
4920
    // Mouse wheel scrolling, scale
4921
22.2k
    UpdateMouseWheel();
4922
4923
    // Mark all windows as not visible and compact unused memory.
4924
22.2k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4925
22.2k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4926
22.2k
    for (ImGuiWindow* window : g.Windows)
4927
66.6k
    {
4928
66.6k
        window->WasActive = window->Active;
4929
66.6k
        window->Active = false;
4930
66.6k
        window->WriteAccessed = false;
4931
66.6k
        window->BeginCountPreviousFrame = window->BeginCount;
4932
66.6k
        window->BeginCount = 0;
4933
4934
        // Garbage collect transient buffers of recently unused windows
4935
66.6k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4936
1
            GcCompactTransientWindowBuffers(window);
4937
66.6k
    }
4938
4939
    // Garbage collect transient buffers of recently unused tables
4940
22.2k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4941
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4942
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4943
22.2k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4944
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4945
0
            TableGcCompactTransientBuffers(&table_temp_data);
4946
22.2k
    if (g.GcCompactAll)
4947
0
        GcCompactTransientMiscBuffers();
4948
22.2k
    g.GcCompactAll = false;
4949
4950
    // Closing the focused window restore focus to the first active root window in descending z-order
4951
22.2k
    if (g.NavWindow && !g.NavWindow->WasActive)
4952
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4953
4954
    // No window should be open at the beginning of the frame.
4955
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4956
22.2k
    g.CurrentWindowStack.resize(0);
4957
22.2k
    g.BeginPopupStack.resize(0);
4958
22.2k
    g.ItemFlagsStack.resize(0);
4959
22.2k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4960
22.2k
    g.GroupStack.resize(0);
4961
4962
    // Docking
4963
22.2k
    DockContextNewFrameUpdateDocking(&g);
4964
4965
    // [DEBUG] Update debug features
4966
22.2k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4967
22.2k
    UpdateDebugToolItemPicker();
4968
22.2k
    UpdateDebugToolStackQueries();
4969
22.2k
    UpdateDebugToolFlashStyleColor();
4970
22.2k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4971
0
    {
4972
0
        g.DebugLocateId = 0;
4973
0
        g.DebugBreakInLocateId = false;
4974
0
    }
4975
22.2k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
4976
0
    {
4977
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
4978
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
4979
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4980
0
    }
4981
22.2k
#endif
4982
4983
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4984
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4985
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4986
22.2k
    g.WithinFrameScopeWithImplicitWindow = true;
4987
22.2k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4988
22.2k
    Begin("Debug##Default");
4989
22.2k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4990
4991
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4992
    // allowing to validate correct Begin/End behavior in user code.
4993
22.2k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4994
22.2k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
4995
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4996
22.2k
    else
4997
22.2k
        g.DebugBeginReturnValueCullDepth = -1;
4998
22.2k
#endif
4999
5000
22.2k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5001
22.2k
}
5002
5003
// FIXME: Add a more explicit sort order in the window structure.
5004
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5005
0
{
5006
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5007
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5008
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5009
0
        return d;
5010
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5011
0
        return d;
5012
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5013
0
}
5014
5015
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5016
66.6k
{
5017
66.6k
    out_sorted_windows->push_back(window);
5018
66.6k
    if (window->Active)
5019
22.6k
    {
5020
22.6k
        int count = window->DC.ChildWindows.Size;
5021
22.6k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5022
23.0k
        for (int i = 0; i < count; i++)
5023
435
        {
5024
435
            ImGuiWindow* child = window->DC.ChildWindows[i];
5025
435
            if (child->Active)
5026
435
                AddWindowToSortBuffer(out_sorted_windows, child);
5027
435
        }
5028
22.6k
    }
5029
66.6k
}
5030
5031
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5032
22.6k
{
5033
22.6k
    ImGuiContext& g = *GImGui;
5034
22.6k
    ImGuiViewportP* viewport = window->Viewport;
5035
22.6k
    IM_ASSERT(viewport != NULL);
5036
22.6k
    g.IO.MetricsRenderWindows++;
5037
22.6k
    if (window->DrawList->_Splitter._Count > 1)
5038
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5039
22.6k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5040
22.6k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5041
434
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5042
434
            AddWindowToDrawData(child, layer);
5043
22.6k
}
5044
5045
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5046
22.2k
{
5047
22.2k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5048
22.2k
}
5049
5050
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5051
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5052
22.2k
{
5053
22.2k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5054
22.2k
}
5055
5056
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5057
22.2k
{
5058
22.2k
    int n = builder->Layers[0]->Size;
5059
22.2k
    int full_size = n;
5060
44.4k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5061
22.2k
        full_size += builder->Layers[i]->Size;
5062
22.2k
    builder->Layers[0]->resize(full_size);
5063
44.4k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5064
22.2k
    {
5065
22.2k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5066
22.2k
        if (layer->empty())
5067
22.2k
            continue;
5068
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5069
0
        n += layer->Size;
5070
0
        layer->resize(0);
5071
0
    }
5072
22.2k
}
5073
5074
static void InitViewportDrawData(ImGuiViewportP* viewport)
5075
22.2k
{
5076
22.2k
    ImGuiIO& io = ImGui::GetIO();
5077
22.2k
    ImDrawData* draw_data = &viewport->DrawDataP;
5078
5079
22.2k
    viewport->DrawData = draw_data; // Make publicly accessible
5080
22.2k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5081
22.2k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5082
22.2k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5083
22.2k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5084
5085
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5086
    // and to allow applications/backends to easily skip rendering.
5087
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5088
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5089
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5090
22.2k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5091
5092
22.2k
    draw_data->Valid = true;
5093
22.2k
    draw_data->CmdListsCount = 0;
5094
22.2k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5095
22.2k
    draw_data->DisplayPos = viewport->Pos;
5096
22.2k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5097
22.2k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5098
22.2k
    draw_data->OwnerViewport = viewport;
5099
22.2k
}
5100
5101
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5102
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5103
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5104
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5105
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5106
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5107
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5108
89.7k
{
5109
89.7k
    ImGuiWindow* window = GetCurrentWindow();
5110
89.7k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5111
89.7k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5112
89.7k
}
5113
5114
void ImGui::PopClipRect()
5115
44.8k
{
5116
44.8k
    ImGuiWindow* window = GetCurrentWindow();
5117
44.8k
    window->DrawList->PopClipRect();
5118
44.8k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5119
44.8k
}
5120
5121
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5122
0
{
5123
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5124
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5125
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5126
0
    return window;
5127
0
}
5128
5129
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5130
0
{
5131
0
    if ((col & IM_COL32_A_MASK) == 0)
5132
0
        return;
5133
5134
0
    ImGuiViewportP* viewport = window->Viewport;
5135
0
    ImRect viewport_rect = viewport->GetMainRect();
5136
5137
    // Draw behind window by moving the draw command at the FRONT of the draw list
5138
0
    {
5139
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5140
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5141
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5142
0
        draw_list->ChannelsMerge();
5143
0
        if (draw_list->CmdBuffer.Size == 0)
5144
0
            draw_list->AddDrawCmd();
5145
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5146
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5147
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5148
0
        IM_ASSERT(cmd.ElemCount == 6);
5149
0
        draw_list->CmdBuffer.pop_back();
5150
0
        draw_list->CmdBuffer.push_front(cmd);
5151
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5152
0
        draw_list->PopClipRect();
5153
0
    }
5154
5155
    // Draw over sibling docking nodes in a same docking tree
5156
0
    if (window->RootWindow->DockIsActive)
5157
0
    {
5158
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5159
0
        draw_list->ChannelsMerge();
5160
0
        if (draw_list->CmdBuffer.Size == 0)
5161
0
            draw_list->AddDrawCmd();
5162
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5163
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5164
0
        draw_list->PopClipRect();
5165
0
    }
5166
0
}
5167
5168
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5169
0
{
5170
0
    ImGuiContext& g = *GImGui;
5171
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5172
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5173
0
    {
5174
0
        ImGuiWindow* window = g.Windows[i];
5175
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5176
0
            continue;
5177
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5178
0
            break;
5179
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5180
0
            bottom_most_visible_window = window;
5181
0
    }
5182
0
    return bottom_most_visible_window;
5183
0
}
5184
5185
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5186
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5187
static void ImGui::RenderDimmedBackgrounds()
5188
22.2k
{
5189
22.2k
    ImGuiContext& g = *GImGui;
5190
22.2k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5191
22.2k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5192
22.2k
        return;
5193
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5194
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5195
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5196
0
        return;
5197
5198
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5199
0
    if (dim_bg_for_modal)
5200
0
    {
5201
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5202
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5203
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5204
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5205
0
    }
5206
0
    else if (dim_bg_for_window_list)
5207
0
    {
5208
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5209
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5210
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5211
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5212
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5213
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5214
5215
        // Draw border around CTRL+Tab target window
5216
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5217
0
        ImGuiViewport* viewport = window->Viewport;
5218
0
        float distance = g.FontSize;
5219
0
        ImRect bb = window->Rect();
5220
0
        bb.Expand(distance);
5221
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5222
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5223
0
        window->DrawList->ChannelsMerge();
5224
0
        if (window->DrawList->CmdBuffer.Size == 0)
5225
0
            window->DrawList->AddDrawCmd();
5226
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5227
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5228
0
        window->DrawList->PopClipRect();
5229
0
    }
5230
5231
    // Draw dimming background on _other_ viewports than the ones our windows are in
5232
0
    for (ImGuiViewportP* viewport : g.Viewports)
5233
0
    {
5234
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5235
0
            continue;
5236
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5237
0
            continue;
5238
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5239
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5240
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5241
0
    }
5242
0
}
5243
5244
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5245
void ImGui::EndFrame()
5246
44.4k
{
5247
44.4k
    ImGuiContext& g = *GImGui;
5248
44.4k
    IM_ASSERT(g.Initialized);
5249
5250
    // Don't process EndFrame() multiple times.
5251
44.4k
    if (g.FrameCountEnded == g.FrameCount)
5252
22.2k
        return;
5253
22.2k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5254
5255
22.2k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5256
5257
22.2k
    ErrorCheckEndFrameSanityChecks();
5258
5259
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5260
22.2k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5261
22.2k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5262
0
    {
5263
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5264
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5265
0
        if (viewport == NULL)
5266
0
            viewport = GetMainViewport();
5267
0
        g.IO.SetPlatformImeDataFn(viewport, ime_data);
5268
0
    }
5269
5270
    // Hide implicit/fallback "Debug" window if it hasn't been used
5271
22.2k
    g.WithinFrameScopeWithImplicitWindow = false;
5272
22.2k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5273
22.2k
        g.CurrentWindow->Active = false;
5274
22.2k
    End();
5275
5276
    // Update navigation: CTRL+Tab, wrap-around requests
5277
22.2k
    NavEndFrame();
5278
5279
    // Update docking
5280
22.2k
    DockContextEndFrame(&g);
5281
5282
22.2k
    SetCurrentViewport(NULL, NULL);
5283
5284
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5285
22.2k
    if (g.DragDropActive)
5286
0
    {
5287
0
        bool is_delivered = g.DragDropPayload.Delivery;
5288
0
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5289
0
        if (is_delivered || is_elapsed)
5290
0
            ClearDragDrop();
5291
0
    }
5292
5293
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5294
22.2k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5295
0
    {
5296
0
        g.DragDropWithinSource = true;
5297
0
        SetTooltip("...");
5298
0
        g.DragDropWithinSource = false;
5299
0
    }
5300
5301
    // End frame
5302
22.2k
    g.WithinFrameScope = false;
5303
22.2k
    g.FrameCountEnded = g.FrameCount;
5304
5305
    // Initiate moving window + handle left-click and right-click focus
5306
22.2k
    UpdateMouseMovingWindowEndFrame();
5307
5308
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5309
22.2k
    UpdateViewportsEndFrame();
5310
5311
    // Sort the window list so that all child windows are after their parent
5312
    // We cannot do that on FocusWindow() because children may not exist yet
5313
22.2k
    g.WindowsTempSortBuffer.resize(0);
5314
22.2k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5315
22.2k
    for (ImGuiWindow* window : g.Windows)
5316
66.6k
    {
5317
66.6k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5318
435
            continue;
5319
66.1k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5320
66.1k
    }
5321
5322
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5323
22.2k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5324
22.2k
    g.Windows.swap(g.WindowsTempSortBuffer);
5325
22.2k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5326
5327
    // Unlock font atlas
5328
22.2k
    g.IO.Fonts->Locked = false;
5329
5330
    // Clear Input data for next frame
5331
22.2k
    g.IO.MousePosPrev = g.IO.MousePos;
5332
22.2k
    g.IO.AppFocusLost = false;
5333
22.2k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5334
22.2k
    g.IO.InputQueueCharacters.resize(0);
5335
5336
22.2k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5337
22.2k
}
5338
5339
// Prepare the data for rendering so you can call GetDrawData()
5340
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5341
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5342
void ImGui::Render()
5343
22.2k
{
5344
22.2k
    ImGuiContext& g = *GImGui;
5345
22.2k
    IM_ASSERT(g.Initialized);
5346
5347
22.2k
    if (g.FrameCountEnded != g.FrameCount)
5348
22.2k
        EndFrame();
5349
22.2k
    if (g.FrameCountRendered == g.FrameCount)
5350
0
        return;
5351
22.2k
    g.FrameCountRendered = g.FrameCount;
5352
5353
22.2k
    g.IO.MetricsRenderWindows = 0;
5354
22.2k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5355
5356
    // Add background ImDrawList (for each active viewport)
5357
22.2k
    for (ImGuiViewportP* viewport : g.Viewports)
5358
22.2k
    {
5359
22.2k
        InitViewportDrawData(viewport);
5360
22.2k
        if (viewport->BgFgDrawLists[0] != NULL)
5361
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5362
22.2k
    }
5363
5364
    // Draw modal/window whitening backgrounds
5365
22.2k
    RenderDimmedBackgrounds();
5366
5367
    // Add ImDrawList to render
5368
22.2k
    ImGuiWindow* windows_to_render_top_most[2];
5369
22.2k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5370
22.2k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5371
22.2k
    for (ImGuiWindow* window : g.Windows)
5372
66.6k
    {
5373
66.6k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5374
66.6k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5375
22.2k
            AddRootWindowToDrawData(window);
5376
66.6k
    }
5377
66.6k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5378
44.4k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5379
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5380
5381
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5382
22.2k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5383
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5384
5385
    // Setup ImDrawData structures for end-user
5386
22.2k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5387
22.2k
    for (ImGuiViewportP* viewport : g.Viewports)
5388
22.2k
    {
5389
22.2k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5390
5391
        // Add foreground ImDrawList (for each active viewport)
5392
22.2k
        if (viewport->BgFgDrawLists[1] != NULL)
5393
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5394
5395
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5396
22.2k
        ImDrawData* draw_data = &viewport->DrawDataP;
5397
22.2k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5398
22.2k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5399
22.6k
            draw_list->_PopUnusedDrawCmd();
5400
5401
22.2k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5402
22.2k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5403
22.2k
    }
5404
5405
22.2k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5406
22.2k
}
5407
5408
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5409
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5410
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5411
44.4k
{
5412
44.4k
    ImGuiContext& g = *GImGui;
5413
5414
44.4k
    const char* text_display_end;
5415
44.4k
    if (hide_text_after_double_hash)
5416
44.4k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5417
0
    else
5418
0
        text_display_end = text_end;
5419
5420
44.4k
    ImFont* font = g.Font;
5421
44.4k
    const float font_size = g.FontSize;
5422
44.4k
    if (text == text_display_end)
5423
0
        return ImVec2(0.0f, font_size);
5424
44.4k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5425
5426
    // Round
5427
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5428
    // FIXME: Investigate using ceilf or e.g.
5429
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5430
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5431
44.4k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5432
5433
44.4k
    return text_size;
5434
44.4k
}
5435
5436
// Find window given position, search front-to-back
5437
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5438
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5439
// called, aka before the next Begin(). Moving window isn't affected.
5440
static void FindHoveredWindow()
5441
22.2k
{
5442
22.2k
    ImGuiContext& g = *GImGui;
5443
5444
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5445
22.2k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5446
22.2k
    if (g.MovingWindow)
5447
22
        g.MovingWindow->Viewport = g.MouseViewport;
5448
5449
22.2k
    ImGuiWindow* hovered_window = NULL;
5450
22.2k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5451
22.2k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5452
22
        hovered_window = g.MovingWindow;
5453
5454
22.2k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5455
22.2k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5456
86.6k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5457
65.5k
    {
5458
65.5k
        ImGuiWindow* window = g.Windows[i];
5459
65.5k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5460
65.5k
        if (!window->Active || window->Hidden)
5461
42.8k
            continue;
5462
22.6k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5463
0
            continue;
5464
22.6k
        IM_ASSERT(window->Viewport);
5465
22.6k
        if (window->Viewport != g.MouseViewport)
5466
0
            continue;
5467
5468
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5469
22.6k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5470
22.6k
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5471
21.5k
            continue;
5472
5473
        // Support for one rectangular hole in any given window
5474
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5475
1.11k
        if (window->HitTestHoleSize.x != 0)
5476
0
        {
5477
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5478
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5479
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5480
0
                continue;
5481
0
        }
5482
5483
1.11k
        if (hovered_window == NULL)
5484
1.11k
            hovered_window = window;
5485
1.11k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5486
1.11k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5487
1.11k
            hovered_window_ignoring_moving_window = window;
5488
1.11k
        if (hovered_window && hovered_window_ignoring_moving_window)
5489
1.11k
            break;
5490
1.11k
    }
5491
5492
22.2k
    g.HoveredWindow = hovered_window;
5493
22.2k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5494
5495
22.2k
    if (g.MovingWindow)
5496
22
        g.MovingWindow->Viewport = moving_window_viewport;
5497
22.2k
}
5498
5499
bool ImGui::IsItemActive()
5500
44.4k
{
5501
44.4k
    ImGuiContext& g = *GImGui;
5502
44.4k
    if (g.ActiveId)
5503
30
        return g.ActiveId == g.LastItemData.ID;
5504
44.3k
    return false;
5505
44.4k
}
5506
5507
bool ImGui::IsItemActivated()
5508
0
{
5509
0
    ImGuiContext& g = *GImGui;
5510
0
    if (g.ActiveId)
5511
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5512
0
            return true;
5513
0
    return false;
5514
0
}
5515
5516
bool ImGui::IsItemDeactivated()
5517
0
{
5518
0
    ImGuiContext& g = *GImGui;
5519
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5520
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5521
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5522
0
}
5523
5524
bool ImGui::IsItemDeactivatedAfterEdit()
5525
0
{
5526
0
    ImGuiContext& g = *GImGui;
5527
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5528
0
}
5529
5530
// == GetItemID() == GetFocusID()
5531
bool ImGui::IsItemFocused()
5532
0
{
5533
0
    ImGuiContext& g = *GImGui;
5534
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5535
0
        return false;
5536
5537
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5538
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5539
0
    ImGuiWindow* window = g.CurrentWindow;
5540
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5541
0
        return false;
5542
5543
0
    return true;
5544
0
}
5545
5546
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5547
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5548
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5549
0
{
5550
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5551
0
}
5552
5553
bool ImGui::IsItemToggledOpen()
5554
0
{
5555
0
    ImGuiContext& g = *GImGui;
5556
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5557
0
}
5558
5559
bool ImGui::IsItemToggledSelection()
5560
0
{
5561
0
    ImGuiContext& g = *GImGui;
5562
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5563
0
}
5564
5565
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5566
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5567
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5568
bool ImGui::IsAnyItemHovered()
5569
0
{
5570
0
    ImGuiContext& g = *GImGui;
5571
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5572
0
}
5573
5574
bool ImGui::IsAnyItemActive()
5575
0
{
5576
0
    ImGuiContext& g = *GImGui;
5577
0
    return g.ActiveId != 0;
5578
0
}
5579
5580
bool ImGui::IsAnyItemFocused()
5581
0
{
5582
0
    ImGuiContext& g = *GImGui;
5583
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5584
0
}
5585
5586
bool ImGui::IsItemVisible()
5587
0
{
5588
0
    ImGuiContext& g = *GImGui;
5589
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5590
0
}
5591
5592
bool ImGui::IsItemEdited()
5593
0
{
5594
0
    ImGuiContext& g = *GImGui;
5595
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5596
0
}
5597
5598
// Allow next item to be overlapped by subsequent items.
5599
// This works by requiring HoveredId to match for two subsequent frames,
5600
// so if a following items overwrite it our interactions will naturally be disabled.
5601
void ImGui::SetNextItemAllowOverlap()
5602
0
{
5603
0
    ImGuiContext& g = *GImGui;
5604
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5605
0
}
5606
5607
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5608
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5609
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5610
void ImGui::SetItemAllowOverlap()
5611
{
5612
    ImGuiContext& g = *GImGui;
5613
    ImGuiID id = g.LastItemData.ID;
5614
    if (g.HoveredId == id)
5615
        g.HoveredIdAllowOverlap = true;
5616
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5617
        g.ActiveIdAllowOverlap = true;
5618
}
5619
#endif
5620
5621
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5622
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5623
22
{
5624
22
    ImGuiContext& g = *GImGui;
5625
22
    IM_ASSERT(g.ActiveId != 0);
5626
22
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5627
22
    g.ActiveIdUsingAllKeyboardKeys = true;
5628
22
    NavMoveRequestCancel();
5629
22
}
5630
5631
ImGuiID ImGui::GetItemID()
5632
0
{
5633
0
    ImGuiContext& g = *GImGui;
5634
0
    return g.LastItemData.ID;
5635
0
}
5636
5637
ImVec2 ImGui::GetItemRectMin()
5638
0
{
5639
0
    ImGuiContext& g = *GImGui;
5640
0
    return g.LastItemData.Rect.Min;
5641
0
}
5642
5643
ImVec2 ImGui::GetItemRectMax()
5644
0
{
5645
0
    ImGuiContext& g = *GImGui;
5646
0
    return g.LastItemData.Rect.Max;
5647
0
}
5648
5649
ImVec2 ImGui::GetItemRectSize()
5650
0
{
5651
0
    ImGuiContext& g = *GImGui;
5652
0
    return g.LastItemData.Rect.GetSize();
5653
0
}
5654
5655
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5656
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5657
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5658
435
{
5659
435
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5660
435
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5661
435
}
5662
5663
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5664
0
{
5665
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5666
0
}
5667
5668
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5669
435
{
5670
435
    ImGuiContext& g = *GImGui;
5671
435
    ImGuiWindow* parent_window = g.CurrentWindow;
5672
435
    IM_ASSERT(id != 0);
5673
5674
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5675
435
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5676
435
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5677
435
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5678
435
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5679
435
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5680
0
    {
5681
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5682
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5683
0
    }
5684
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5685
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5686
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5687
#endif
5688
435
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5689
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5690
435
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5691
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5692
5693
    // Set window flags
5694
435
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5695
435
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5696
435
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5697
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5698
435
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5699
435
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5700
5701
    // Special framed style
5702
435
    if (child_flags & ImGuiChildFlags_FrameStyle)
5703
0
    {
5704
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5705
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5706
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5707
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5708
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5709
0
        window_flags |= ImGuiWindowFlags_NoMove;
5710
0
    }
5711
5712
    // Forward child flags
5713
435
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5714
435
    g.NextWindowData.ChildFlags = child_flags;
5715
5716
    // Forward size
5717
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5718
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5719
435
    const ImVec2 size_avail = GetContentRegionAvail();
5720
435
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5721
435
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5722
435
    SetNextWindowSize(size);
5723
5724
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5725
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5726
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5727
435
    const char* temp_window_name;
5728
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5729
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5730
    else*/
5731
435
    if (name)
5732
435
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5733
0
    else
5734
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5735
5736
    // Set style
5737
435
    const float backup_border_size = g.Style.ChildBorderSize;
5738
435
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5739
253
        g.Style.ChildBorderSize = 0.0f;
5740
5741
    // Begin into window
5742
435
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5743
5744
    // Restore style
5745
435
    g.Style.ChildBorderSize = backup_border_size;
5746
435
    if (child_flags & ImGuiChildFlags_FrameStyle)
5747
0
    {
5748
0
        PopStyleVar(3);
5749
0
        PopStyleColor();
5750
0
    }
5751
5752
435
    ImGuiWindow* child_window = g.CurrentWindow;
5753
435
    child_window->ChildId = id;
5754
5755
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5756
    // While this is not really documented/defined, it seems that the expected thing to do.
5757
435
    if (child_window->BeginCount == 1)
5758
435
        parent_window->DC.CursorPos = child_window->Pos;
5759
5760
    // Process navigation-in immediately so NavInit can run on first frame
5761
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5762
435
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5763
435
    if (g.ActiveId == temp_id_for_activation)
5764
0
        ClearActiveID();
5765
435
    if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5766
0
    {
5767
0
        FocusWindow(child_window);
5768
0
        NavInitWindow(child_window, false);
5769
0
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5770
0
        g.ActiveIdSource = g.NavInputSource;
5771
0
    }
5772
435
    return ret;
5773
435
}
5774
5775
void ImGui::EndChild()
5776
435
{
5777
435
    ImGuiContext& g = *GImGui;
5778
435
    ImGuiWindow* child_window = g.CurrentWindow;
5779
5780
435
    IM_ASSERT(g.WithinEndChild == false);
5781
435
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5782
5783
435
    g.WithinEndChild = true;
5784
435
    ImVec2 child_size = child_window->Size;
5785
435
    End();
5786
435
    if (child_window->BeginCount == 1)
5787
435
    {
5788
435
        ImGuiWindow* parent_window = g.CurrentWindow;
5789
435
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5790
435
        ItemSize(child_size);
5791
435
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5792
383
        {
5793
383
            ItemAdd(bb, child_window->ChildId);
5794
383
            RenderNavHighlight(bb, child_window->ChildId);
5795
5796
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5797
383
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5798
44
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5799
383
        }
5800
52
        else
5801
52
        {
5802
            // Not navigable into
5803
52
            ItemAdd(bb, 0);
5804
5805
            // But when flattened we directly reach items, adjust active layer mask accordingly
5806
52
            if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5807
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5808
52
        }
5809
435
        if (g.HoveredWindow == child_window)
5810
1
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5811
435
    }
5812
435
    g.WithinEndChild = false;
5813
435
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5814
435
}
5815
5816
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5817
10
{
5818
10
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5819
10
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5820
10
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5821
10
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5822
10
}
5823
5824
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5825
44.8k
{
5826
44.8k
    ImGuiContext& g = *GImGui;
5827
44.8k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5828
44.8k
}
5829
5830
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5831
44.8k
{
5832
44.8k
    ImGuiID id = ImHashStr(name);
5833
44.8k
    return FindWindowByID(id);
5834
44.8k
}
5835
5836
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5837
0
{
5838
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5839
0
    window->ViewportPos = main_viewport->Pos;
5840
0
    if (settings->ViewportId)
5841
0
    {
5842
0
        window->ViewportId = settings->ViewportId;
5843
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5844
0
    }
5845
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5846
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5847
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5848
0
    window->Collapsed = settings->Collapsed;
5849
0
    window->DockId = settings->DockId;
5850
0
    window->DockOrder = settings->DockOrder;
5851
0
}
5852
5853
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5854
44.8k
{
5855
44.8k
    ImGuiContext& g = *GImGui;
5856
5857
44.8k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5858
44.8k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5859
44.8k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5860
2
    {
5861
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5862
2
        g.WindowsFocusOrder.push_back(window);
5863
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5864
2
    }
5865
44.8k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5866
0
    {
5867
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5868
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5869
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5870
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5871
0
        window->FocusOrder = -1;
5872
0
    }
5873
44.8k
    window->IsExplicitChild = new_is_explicit_child;
5874
44.8k
}
5875
5876
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5877
3
{
5878
    // Initial window state with e.g. default/arbitrary window position
5879
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5880
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5881
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5882
3
    window->Size = window->SizeFull = ImVec2(0, 0);
5883
3
    window->ViewportPos = main_viewport->Pos;
5884
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5885
5886
3
    if (settings != NULL)
5887
0
    {
5888
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5889
0
        ApplyWindowSettings(window, settings);
5890
0
    }
5891
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5892
5893
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5894
0
    {
5895
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5896
0
        window->AutoFitOnlyGrows = false;
5897
0
    }
5898
3
    else
5899
3
    {
5900
3
        if (window->Size.x <= 0.0f)
5901
3
            window->AutoFitFramesX = 2;
5902
3
        if (window->Size.y <= 0.0f)
5903
3
            window->AutoFitFramesY = 2;
5904
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5905
3
    }
5906
3
}
5907
5908
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5909
3
{
5910
    // Create window the first time
5911
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5912
3
    ImGuiContext& g = *GImGui;
5913
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5914
3
    window->Flags = flags;
5915
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5916
5917
3
    ImGuiWindowSettings* settings = NULL;
5918
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5919
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5920
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5921
5922
3
    InitOrLoadWindowSettings(window, settings);
5923
5924
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5925
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5926
3
    else
5927
3
        g.Windows.push_back(window);
5928
5929
3
    return window;
5930
3
}
5931
5932
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5933
0
{
5934
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5935
0
}
5936
5937
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5938
134k
{
5939
134k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5940
134k
}
5941
5942
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5943
134k
{
5944
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5945
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
5946
    // Perhaps should tend further a neater test for this.
5947
134k
    ImGuiContext& g = *GImGui;
5948
134k
    ImVec2 size_min;
5949
134k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
5950
1.30k
    {
5951
1.30k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5952
1.30k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5953
1.30k
    }
5954
133k
    else
5955
133k
    {
5956
133k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5957
133k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5958
133k
    }
5959
5960
    // Reduce artifacts with very small windows
5961
134k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5962
134k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
5963
134k
    return size_min;
5964
134k
}
5965
5966
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5967
89.7k
{
5968
89.7k
    ImGuiContext& g = *GImGui;
5969
89.7k
    ImVec2 new_size = size_desired;
5970
89.7k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5971
0
    {
5972
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
5973
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5974
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5975
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5976
0
        if (g.NextWindowData.SizeCallback)
5977
0
        {
5978
0
            ImGuiSizeCallbackData data;
5979
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5980
0
            data.Pos = window->Pos;
5981
0
            data.CurrentSize = window->SizeFull;
5982
0
            data.DesiredSize = new_size;
5983
0
            g.NextWindowData.SizeCallback(&data);
5984
0
            new_size = data.DesiredSize;
5985
0
        }
5986
0
        new_size.x = IM_TRUNC(new_size.x);
5987
0
        new_size.y = IM_TRUNC(new_size.y);
5988
0
    }
5989
5990
    // Minimum size
5991
89.7k
    ImVec2 size_min = CalcWindowMinSize(window);
5992
89.7k
    return ImMax(new_size, size_min);
5993
89.7k
}
5994
5995
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5996
44.8k
{
5997
44.8k
    bool preserve_old_content_sizes = false;
5998
44.8k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5999
21.7k
        preserve_old_content_sizes = true;
6000
23.0k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6001
0
        preserve_old_content_sizes = true;
6002
44.8k
    if (preserve_old_content_sizes)
6003
21.7k
    {
6004
21.7k
        *content_size_current = window->ContentSize;
6005
21.7k
        *content_size_ideal = window->ContentSizeIdeal;
6006
21.7k
        return;
6007
21.7k
    }
6008
6009
23.0k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6010
23.0k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6011
23.0k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6012
23.0k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6013
23.0k
}
6014
6015
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6016
44.8k
{
6017
44.8k
    ImGuiContext& g = *GImGui;
6018
44.8k
    ImGuiStyle& style = g.Style;
6019
44.8k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6020
44.8k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6021
44.8k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6022
44.8k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6023
44.8k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6024
0
    {
6025
        // Tooltip always resize
6026
0
        return size_desired;
6027
0
    }
6028
44.8k
    else
6029
44.8k
    {
6030
        // Maximum window size is determined by the viewport size or monitor size
6031
44.8k
        ImVec2 size_min = CalcWindowMinSize(window);
6032
44.8k
        ImVec2 size_max = (window->ViewportOwned || ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6033
44.8k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6034
44.8k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0)
6035
0
            size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6036
44.8k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6037
6038
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6039
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6040
44.8k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6041
44.8k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6042
44.8k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6043
44.8k
        if (will_have_scrollbar_x)
6044
435
            size_auto_fit.y += style.ScrollbarSize;
6045
44.8k
        if (will_have_scrollbar_y)
6046
21
            size_auto_fit.x += style.ScrollbarSize;
6047
44.8k
        return size_auto_fit;
6048
44.8k
    }
6049
44.8k
}
6050
6051
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6052
0
{
6053
0
    ImVec2 size_contents_current;
6054
0
    ImVec2 size_contents_ideal;
6055
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6056
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6057
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6058
0
    return size_final;
6059
0
}
6060
6061
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6062
23.0k
{
6063
23.0k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6064
0
        return ImGuiCol_PopupBg;
6065
23.0k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6066
435
        return ImGuiCol_ChildBg;
6067
22.6k
    return ImGuiCol_WindowBg;
6068
23.0k
}
6069
6070
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6071
0
{
6072
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6073
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6074
0
    ImVec2 size_expected = pos_max - pos_min;
6075
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6076
0
    *out_pos = pos_min;
6077
0
    if (corner_norm.x == 0.0f)
6078
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6079
0
    if (corner_norm.y == 0.0f)
6080
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6081
0
    *out_size = size_constrained;
6082
0
}
6083
6084
// Data for resizing from resize grip / corner
6085
struct ImGuiResizeGripDef
6086
{
6087
    ImVec2  CornerPosN;
6088
    ImVec2  InnerDir;
6089
    int     AngleMin12, AngleMax12;
6090
};
6091
static const ImGuiResizeGripDef resize_grip_def[4] =
6092
{
6093
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6094
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6095
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6096
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6097
};
6098
6099
// Data for resizing from borders
6100
struct ImGuiResizeBorderDef
6101
{
6102
    ImVec2  InnerDir;               // Normal toward inside
6103
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6104
    float   OuterAngle;             // Angle toward outside
6105
};
6106
static const ImGuiResizeBorderDef resize_border_def[4] =
6107
{
6108
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6109
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6110
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6111
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6112
};
6113
6114
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6115
0
{
6116
0
    ImRect rect = window->Rect();
6117
0
    if (thickness == 0.0f)
6118
0
        rect.Max -= ImVec2(1, 1);
6119
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6120
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6121
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6122
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6123
0
    IM_ASSERT(0);
6124
0
    return ImRect();
6125
0
}
6126
6127
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6128
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6129
0
{
6130
0
    IM_ASSERT(n >= 0 && n < 4);
6131
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6132
0
    id = ImHashStr("#RESIZE", 0, id);
6133
0
    id = ImHashData(&n, sizeof(int), id);
6134
0
    return id;
6135
0
}
6136
6137
// Borders (Left, Right, Up, Down)
6138
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6139
0
{
6140
0
    IM_ASSERT(dir >= 0 && dir < 4);
6141
0
    int n = (int)dir + 4;
6142
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6143
0
    id = ImHashStr("#RESIZE", 0, id);
6144
0
    id = ImHashData(&n, sizeof(int), id);
6145
0
    return id;
6146
0
}
6147
6148
// Handle resize for: Resize Grips, Borders, Gamepad
6149
// Return true when using auto-fit (double-click on resize grip)
6150
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6151
23.0k
{
6152
23.0k
    ImGuiContext& g = *GImGui;
6153
23.0k
    ImGuiWindowFlags flags = window->Flags;
6154
6155
23.0k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6156
437
        return false;
6157
22.6k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6158
22.2k
        return false;
6159
6160
433
    int ret_auto_fit_mask = 0x00;
6161
433
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6162
433
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6163
433
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6164
6165
433
    ImRect clamp_rect = visibility_rect;
6166
433
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6167
433
    if (window_move_from_title_bar)
6168
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6169
6170
433
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6171
433
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6172
6173
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6174
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6175
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6176
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6177
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6178
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6179
433
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6180
433
    if (clip_with_viewport_rect)
6181
433
        window->ClipRect = window->Viewport->GetMainRect();
6182
6183
    // Resize grips and borders are on layer 1
6184
433
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6185
6186
    // Manual resize grips
6187
433
    PushID("#RESIZE");
6188
866
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6189
433
    {
6190
433
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6191
433
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6192
6193
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6194
433
        bool hovered, held;
6195
433
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6196
433
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6197
433
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6198
433
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6199
433
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6200
433
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6201
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6202
433
        if (hovered || held)
6203
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6204
6205
433
        if (held && g.IO.MouseDoubleClicked[0])
6206
0
        {
6207
            // Auto-fit when double-clicking
6208
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6209
0
            ret_auto_fit_mask = 0x03; // Both axises
6210
0
            ClearActiveID();
6211
0
        }
6212
433
        else if (held)
6213
0
        {
6214
            // Resize from any of the four corners
6215
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6216
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6217
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6218
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6219
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6220
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6221
0
        }
6222
6223
        // Only lower-left grip is visible before hovering/activating
6224
433
        if (resize_grip_n == 0 || held || hovered)
6225
433
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6226
433
    }
6227
6228
433
    int resize_border_mask = 0x00;
6229
433
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6230
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6231
433
    else
6232
433
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6233
2.16k
    for (int border_n = 0; border_n < 4; border_n++)
6234
1.73k
    {
6235
1.73k
        if ((resize_border_mask & (1 << border_n)) == 0)
6236
1.73k
            continue;
6237
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6238
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6239
6240
0
        bool hovered, held;
6241
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6242
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6243
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6244
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6245
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6246
0
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6247
0
            hovered = false;
6248
0
        if (hovered || held)
6249
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6250
0
        if (held && g.IO.MouseDoubleClicked[0])
6251
0
        {
6252
            // Double-clicking bottom or right border auto-fit on this axis
6253
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6254
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6255
0
            {
6256
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6257
0
                ret_auto_fit_mask |= (1 << axis);
6258
0
                hovered = held = false; // So border doesn't show highlighted at new position
6259
0
            }
6260
0
            ClearActiveID();
6261
0
        }
6262
0
        else if (held)
6263
0
        {
6264
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6265
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6266
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6267
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6268
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6269
0
            {
6270
0
                g.WindowResizeBorderExpectedRect = border_rect;
6271
0
                g.WindowResizeRelativeMode = false;
6272
0
            }
6273
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6274
0
                g.WindowResizeRelativeMode = true;
6275
6276
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6277
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6278
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6279
6280
            // Use absolute mode position
6281
0
            ImVec2 border_target = window->Pos;
6282
0
            border_target[axis] = border_target_abs_mode_for_axis;
6283
6284
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6285
0
            bool ignore_resize = false;
6286
0
            if (g.WindowResizeRelativeMode)
6287
0
            {
6288
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6289
0
                border_target[axis] = border_target_rel_mode_for_axis;
6290
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6291
0
                    ignore_resize = true;
6292
0
            }
6293
6294
            // Clamp, apply
6295
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6296
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6297
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6298
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6299
0
            {
6300
0
                ImGuiWindowFlags parent_flags = window->ParentWindow->Flags;
6301
0
                ImRect border_limit_rect = window->ParentWindow->InnerRect;
6302
0
                border_limit_rect.Expand(ImVec2(-ImMax(window->WindowPadding.x, window->WindowBorderSize), -ImMax(window->WindowPadding.y, window->WindowBorderSize)));
6303
0
                if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))
6304
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6305
0
                if (parent_flags & ImGuiWindowFlags_NoScrollbar)
6306
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6307
0
            }
6308
0
            if (!ignore_resize)
6309
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6310
0
        }
6311
0
        if (hovered)
6312
0
            *border_hovered = border_n;
6313
0
        if (held)
6314
0
            *border_held = border_n;
6315
0
    }
6316
433
    PopID();
6317
6318
    // Restore nav layer
6319
433
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6320
6321
    // Navigation resize (keyboard/gamepad)
6322
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6323
    // Not even sure the callback works here.
6324
433
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6325
0
    {
6326
0
        ImVec2 nav_resize_dir;
6327
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6328
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6329
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6330
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6331
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6332
0
        {
6333
0
            const float NAV_RESIZE_SPEED = 600.0f;
6334
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6335
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6336
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6337
0
            g.NavWindowingToggleLayer = false;
6338
0
            g.NavDisableMouseHover = true;
6339
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6340
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6341
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6342
0
            {
6343
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6344
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6345
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6346
0
            }
6347
0
        }
6348
0
    }
6349
6350
    // Apply back modified position/size to window
6351
433
    const ImVec2 curr_pos = window->Pos;
6352
433
    const ImVec2 curr_size = window->SizeFull;
6353
433
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6354
0
        window->Size.x = window->SizeFull.x = size_target.x;
6355
433
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6356
0
        window->Size.y = window->SizeFull.y = size_target.y;
6357
433
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6358
0
        window->Pos.x = ImTrunc(pos_target.x);
6359
433
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6360
0
        window->Pos.y = ImTrunc(pos_target.y);
6361
433
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6362
0
        MarkIniSettingsDirty(window);
6363
6364
    // Recalculate next expected border expected coordinates
6365
433
    if (*border_held != -1)
6366
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6367
6368
433
    return ret_auto_fit_mask;
6369
22.6k
}
6370
6371
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6372
44.4k
{
6373
44.4k
    ImGuiContext& g = *GImGui;
6374
44.4k
    ImVec2 size_for_clamping = window->Size;
6375
44.4k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6376
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6377
44.4k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6378
44.4k
}
6379
6380
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6381
0
{
6382
0
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6383
0
    const float rounding = window->WindowRounding;
6384
0
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6385
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6386
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6387
0
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6388
0
}
6389
6390
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6391
23.0k
{
6392
23.0k
    ImGuiContext& g = *GImGui;
6393
23.0k
    const float border_size = window->WindowBorderSize;
6394
23.0k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6395
23.0k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6396
22.8k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6397
253
    else if (border_size > 0.0f)
6398
0
    {
6399
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6400
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6401
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6402
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6403
0
    }
6404
23.0k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6405
0
    {
6406
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6407
0
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6408
0
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6409
0
    }
6410
23.0k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6411
0
    {
6412
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6413
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6414
0
    }
6415
23.0k
}
6416
6417
// Draw background and borders
6418
// Draw and handle scrollbars
6419
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6420
44.8k
{
6421
44.8k
    ImGuiContext& g = *GImGui;
6422
44.8k
    ImGuiStyle& style = g.Style;
6423
44.8k
    ImGuiWindowFlags flags = window->Flags;
6424
6425
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6426
44.8k
    IM_ASSERT(window->BeginCount == 0);
6427
44.8k
    window->SkipItems = false;
6428
6429
    // Draw window + handle manual resize
6430
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6431
44.8k
    const float window_rounding = window->WindowRounding;
6432
44.8k
    const float window_border_size = window->WindowBorderSize;
6433
44.8k
    if (window->Collapsed)
6434
21.7k
    {
6435
        // Title bar only
6436
21.7k
        const float backup_border_size = style.FrameBorderSize;
6437
21.7k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6438
21.7k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6439
21.7k
        if (window->ViewportOwned)
6440
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6441
21.7k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6442
21.7k
        g.Style.FrameBorderSize = backup_border_size;
6443
21.7k
    }
6444
23.0k
    else
6445
23.0k
    {
6446
        // Window background
6447
23.0k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6448
23.0k
        {
6449
23.0k
            bool is_docking_transparent_payload = false;
6450
23.0k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6451
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6452
0
                    is_docking_transparent_payload = true;
6453
6454
23.0k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6455
23.0k
            if (window->ViewportOwned)
6456
0
            {
6457
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6458
0
                if (is_docking_transparent_payload)
6459
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6460
0
            }
6461
23.0k
            else
6462
23.0k
            {
6463
                // Adjust alpha. For docking
6464
23.0k
                bool override_alpha = false;
6465
23.0k
                float alpha = 1.0f;
6466
23.0k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6467
0
                {
6468
0
                    alpha = g.NextWindowData.BgAlphaVal;
6469
0
                    override_alpha = true;
6470
0
                }
6471
23.0k
                if (is_docking_transparent_payload)
6472
0
                {
6473
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6474
0
                    override_alpha = true;
6475
0
                }
6476
23.0k
                if (override_alpha)
6477
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6478
23.0k
            }
6479
6480
            // Render, for docked windows and host windows we ensure bg goes before decorations
6481
23.0k
            if (window->DockIsActive)
6482
0
                window->DockNode->LastBgColor = bg_col;
6483
23.0k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6484
23.0k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6485
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6486
23.0k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6487
23.0k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6488
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6489
23.0k
        }
6490
23.0k
        if (window->DockIsActive)
6491
0
            window->DockNode->IsBgDrawnThisFrame = true;
6492
6493
        // Title bar
6494
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6495
        // in order for their pos/size to be matching their undocking state.)
6496
23.0k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6497
22.6k
        {
6498
22.6k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6499
22.6k
            if (window->ViewportOwned)
6500
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6501
22.6k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6502
22.6k
        }
6503
6504
        // Menu bar
6505
23.0k
        if (flags & ImGuiWindowFlags_MenuBar)
6506
0
        {
6507
0
            ImRect menu_bar_rect = window->MenuBarRect();
6508
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6509
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6510
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6511
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6512
0
        }
6513
6514
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6515
23.0k
        ImGuiDockNode* node = window->DockNode;
6516
23.0k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6517
0
        {
6518
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6519
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6520
0
            ImVec2 p = node->Pos;
6521
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6522
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6523
0
            KeepAliveID(unhide_id);
6524
0
            bool hovered, held;
6525
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6526
0
                node->WantHiddenTabBarToggle = true;
6527
0
            else if (held && IsMouseDragging(0))
6528
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6529
6530
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6531
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6532
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6533
0
        }
6534
6535
        // Scrollbars
6536
23.0k
        if (window->ScrollbarX)
6537
435
            Scrollbar(ImGuiAxis_X);
6538
23.0k
        if (window->ScrollbarY)
6539
441
            Scrollbar(ImGuiAxis_Y);
6540
6541
        // Render resize grips (after their input handling so we don't have a frame of latency)
6542
23.0k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6543
22.6k
        {
6544
45.2k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6545
22.6k
            {
6546
22.6k
                const ImU32 col = resize_grip_col[resize_grip_n];
6547
22.6k
                if ((col & IM_COL32_A_MASK) == 0)
6548
22.2k
                    continue;
6549
433
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6550
433
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6551
433
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6552
433
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6553
433
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6554
433
                window->DrawList->PathFillConvex(col);
6555
433
            }
6556
22.6k
        }
6557
6558
        // Borders (for dock node host they will be rendered over after the tab bar)
6559
23.0k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6560
23.0k
            RenderWindowOuterBorders(window);
6561
23.0k
    }
6562
44.8k
}
6563
6564
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6565
// Render title text, collapse button, close button
6566
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6567
44.4k
{
6568
44.4k
    ImGuiContext& g = *GImGui;
6569
44.4k
    ImGuiStyle& style = g.Style;
6570
44.4k
    ImGuiWindowFlags flags = window->Flags;
6571
6572
44.4k
    const bool has_close_button = (p_open != NULL);
6573
44.4k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6574
6575
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6576
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6577
44.4k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6578
44.4k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6579
44.4k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6580
6581
    // Layout buttons
6582
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6583
44.4k
    float pad_l = style.FramePadding.x;
6584
44.4k
    float pad_r = style.FramePadding.x;
6585
44.4k
    float button_sz = g.FontSize;
6586
44.4k
    ImVec2 close_button_pos;
6587
44.4k
    ImVec2 collapse_button_pos;
6588
44.4k
    if (has_close_button)
6589
0
    {
6590
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6591
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6592
0
    }
6593
44.4k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6594
0
    {
6595
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6596
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6597
0
    }
6598
44.4k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6599
44.4k
    {
6600
44.4k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6601
44.4k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6602
44.4k
    }
6603
6604
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6605
44.4k
    if (has_collapse_button)
6606
44.4k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6607
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6608
6609
    // Close button
6610
44.4k
    if (has_close_button)
6611
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6612
0
            *p_open = false;
6613
6614
44.4k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6615
44.4k
    g.CurrentItemFlags = item_flags_backup;
6616
6617
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6618
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6619
44.4k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6620
44.4k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6621
6622
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6623
    // while uncentered title text will still reach edges correctly.
6624
44.4k
    if (pad_l > style.FramePadding.x)
6625
44.4k
        pad_l += g.Style.ItemInnerSpacing.x;
6626
44.4k
    if (pad_r > style.FramePadding.x)
6627
0
        pad_r += g.Style.ItemInnerSpacing.x;
6628
44.4k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6629
0
    {
6630
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6631
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6632
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6633
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6634
0
    }
6635
6636
44.4k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6637
44.4k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6638
44.4k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6639
0
    {
6640
0
        ImVec2 marker_pos;
6641
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6642
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6643
0
        if (marker_pos.x > layout_r.Min.x)
6644
0
        {
6645
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6646
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6647
0
        }
6648
0
    }
6649
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6650
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6651
44.4k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6652
44.4k
}
6653
6654
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6655
44.8k
{
6656
44.8k
    window->ParentWindow = parent_window;
6657
44.8k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6658
44.8k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6659
435
    {
6660
435
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6661
435
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6662
435
            window->RootWindow = parent_window->RootWindow;
6663
435
    }
6664
44.8k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6665
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6666
44.8k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6667
435
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6668
44.8k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6669
0
    {
6670
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6671
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6672
0
    }
6673
44.8k
}
6674
6675
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6676
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6677
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6678
// - WindowA            // FindBlockingModal() returns Modal1
6679
//   - WindowB          //                  .. returns Modal1
6680
//   - Modal1           //                  .. returns Modal2
6681
//      - WindowC       //                  .. returns Modal2
6682
//          - WindowD   //                  .. returns Modal2
6683
//          - Modal2    //                  .. returns Modal2
6684
//            - WindowE //                  .. returns NULL
6685
// Notes:
6686
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6687
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6688
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6689
2
{
6690
2
    ImGuiContext& g = *GImGui;
6691
2
    if (g.OpenPopupStack.Size <= 0)
6692
2
        return NULL;
6693
6694
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6695
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6696
0
    {
6697
0
        ImGuiWindow* popup_window = popup_data.Window;
6698
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6699
0
            continue;
6700
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6701
0
            continue;
6702
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6703
0
            return popup_window;
6704
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6705
0
            continue;
6706
0
        return popup_window;                                        // Place window right below first block modal
6707
0
    }
6708
0
    return NULL;
6709
0
}
6710
6711
// Push a new Dear ImGui window to add widgets to.
6712
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6713
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6714
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6715
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6716
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6717
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6718
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6719
44.8k
{
6720
44.8k
    ImGuiContext& g = *GImGui;
6721
44.8k
    const ImGuiStyle& style = g.Style;
6722
44.8k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6723
44.8k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6724
44.8k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6725
6726
    // Find or create
6727
44.8k
    ImGuiWindow* window = FindWindowByName(name);
6728
44.8k
    const bool window_just_created = (window == NULL);
6729
44.8k
    if (window_just_created)
6730
3
        window = CreateNewWindow(name, flags);
6731
6732
    // [DEBUG] Debug break requested by user
6733
44.8k
    if (g.DebugBreakInWindow == window->ID)
6734
0
        IM_DEBUG_BREAK();
6735
6736
    // Automatically disable manual moving/resizing when NoInputs is set
6737
44.8k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6738
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6739
6740
44.8k
    if (flags & ImGuiWindowFlags_NavFlattened)
6741
44.8k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6742
6743
44.8k
    const int current_frame = g.FrameCount;
6744
44.8k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6745
44.8k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6746
6747
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6748
44.8k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6749
44.8k
    if (flags & ImGuiWindowFlags_Popup)
6750
0
    {
6751
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6752
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6753
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6754
0
    }
6755
6756
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6757
44.8k
    const bool window_was_appearing = window->Appearing;
6758
44.8k
    if (first_begin_of_the_frame)
6759
44.8k
    {
6760
44.8k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6761
44.8k
        window->Appearing = window_just_activated_by_user;
6762
44.8k
        if (window->Appearing)
6763
5
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6764
44.8k
        window->FlagsPreviousFrame = window->Flags;
6765
44.8k
        window->Flags = (ImGuiWindowFlags)flags;
6766
44.8k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6767
44.8k
        window->LastFrameActive = current_frame;
6768
44.8k
        window->LastTimeActive = (float)g.Time;
6769
44.8k
        window->BeginOrderWithinParent = 0;
6770
44.8k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6771
44.8k
    }
6772
0
    else
6773
0
    {
6774
0
        flags = window->Flags;
6775
0
    }
6776
6777
    // Docking
6778
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6779
44.8k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6780
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6781
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6782
44.8k
    if (first_begin_of_the_frame)
6783
44.8k
    {
6784
44.8k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6785
44.8k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6786
44.8k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6787
44.8k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6788
44.8k
        if (has_dock_node || new_auto_dock_node)
6789
0
        {
6790
0
            BeginDocked(window, p_open);
6791
0
            flags = window->Flags;
6792
0
            if (window->DockIsActive)
6793
0
            {
6794
0
                IM_ASSERT(window->DockNode != NULL);
6795
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6796
0
            }
6797
6798
            // Amend the Appearing flag
6799
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6800
0
            {
6801
0
                window->Appearing = true;
6802
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6803
0
            }
6804
0
        }
6805
44.8k
        else
6806
44.8k
        {
6807
44.8k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6808
44.8k
        }
6809
44.8k
    }
6810
6811
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6812
44.8k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6813
44.8k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6814
44.8k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6815
6816
    // We allow window memory to be compacted so recreate the base stack when needed.
6817
44.8k
    if (window->IDStack.Size == 0)
6818
0
        window->IDStack.push_back(window->ID);
6819
6820
    // Add to stack
6821
44.8k
    g.CurrentWindow = window;
6822
44.8k
    ImGuiWindowStackData window_stack_data;
6823
44.8k
    window_stack_data.Window = window;
6824
44.8k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6825
44.8k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6826
44.8k
    g.CurrentWindowStack.push_back(window_stack_data);
6827
44.8k
    if (flags & ImGuiWindowFlags_ChildMenu)
6828
0
        g.BeginMenuDepth++;
6829
6830
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6831
44.8k
    if (first_begin_of_the_frame)
6832
44.8k
    {
6833
44.8k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6834
44.8k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6835
6836
        // Focus route
6837
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
6838
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
6839
44.8k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
6840
44.8k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
6841
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
6842
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
6843
6844
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
6845
44.8k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
6846
0
        {
6847
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
6848
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
6849
0
        }
6850
44.8k
    }
6851
6852
    // Add to focus scope stack
6853
44.8k
    PushFocusScope((flags & ImGuiWindowFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
6854
44.8k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6855
6856
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
6857
44.8k
    if (flags & ImGuiWindowFlags_Popup)
6858
0
    {
6859
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6860
0
        popup_ref.Window = window;
6861
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6862
0
        g.BeginPopupStack.push_back(popup_ref);
6863
0
        window->PopupId = popup_ref.PopupId;
6864
0
    }
6865
6866
    // Process SetNextWindow***() calls
6867
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6868
44.8k
    bool window_pos_set_by_api = false;
6869
44.8k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6870
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6871
0
    {
6872
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6873
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6874
0
        {
6875
            // May be processed on the next frame if this is our first frame and we are measuring size
6876
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6877
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6878
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6879
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6880
0
        }
6881
0
        else
6882
0
        {
6883
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6884
0
        }
6885
0
    }
6886
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6887
22.6k
    {
6888
22.6k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6889
22.6k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6890
22.6k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6891
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
6892
22.6k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6893
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
6894
22.6k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6895
22.6k
    }
6896
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6897
0
    {
6898
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6899
0
        {
6900
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6901
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6902
0
        }
6903
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6904
0
        {
6905
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6906
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6907
0
        }
6908
0
    }
6909
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6910
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6911
44.8k
    else if (first_begin_of_the_frame)
6912
44.8k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6913
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6914
0
        window->WindowClass = g.NextWindowData.WindowClass;
6915
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6916
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6917
44.8k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6918
0
        FocusWindow(window);
6919
44.8k
    if (window->Appearing)
6920
5
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6921
6922
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6923
44.8k
    g.CurrentWindow = NULL;
6924
6925
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6926
44.8k
    if (first_begin_of_the_frame)
6927
44.8k
    {
6928
        // Initialize
6929
44.8k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6930
44.8k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6931
44.8k
        window->Active = true;
6932
44.8k
        window->HasCloseButton = (p_open != NULL);
6933
44.8k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6934
44.8k
        window->IDStack.resize(1);
6935
44.8k
        window->DrawList->_ResetForNewFrame();
6936
44.8k
        window->DC.CurrentTableIdx = -1;
6937
44.8k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6938
0
        {
6939
0
            window->DrawList->ChannelsSplit(2);
6940
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6941
0
        }
6942
6943
        // Restore buffer capacity when woken from a compacted state, to avoid
6944
44.8k
        if (window->MemoryCompacted)
6945
0
            GcAwakeTransientWindowBuffers(window);
6946
6947
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6948
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6949
44.8k
        bool window_title_visible_elsewhere = false;
6950
44.8k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6951
0
            window_title_visible_elsewhere = true;
6952
44.8k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6953
0
            window_title_visible_elsewhere = true;
6954
44.8k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6955
0
        {
6956
0
            size_t buf_len = (size_t)window->NameBufLen;
6957
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6958
0
            window->NameBufLen = (int)buf_len;
6959
0
        }
6960
6961
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6962
6963
        // Update contents size from last frame for auto-fitting (or use explicit size)
6964
44.8k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6965
6966
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6967
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6968
        // it has a single usage before this code block and may be set below before it is finally checked.
6969
44.8k
        if (window->HiddenFramesCanSkipItems > 0)
6970
0
            window->HiddenFramesCanSkipItems--;
6971
44.8k
        if (window->HiddenFramesCannotSkipItems > 0)
6972
2
            window->HiddenFramesCannotSkipItems--;
6973
44.8k
        if (window->HiddenFramesForRenderOnly > 0)
6974
0
            window->HiddenFramesForRenderOnly--;
6975
6976
        // Hide new windows for one frame until they calculate their size
6977
44.8k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6978
1
            window->HiddenFramesCannotSkipItems = 1;
6979
6980
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6981
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6982
44.8k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6983
0
        {
6984
0
            window->HiddenFramesCannotSkipItems = 1;
6985
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6986
0
            {
6987
0
                if (!window_size_x_set_by_api)
6988
0
                    window->Size.x = window->SizeFull.x = 0.f;
6989
0
                if (!window_size_y_set_by_api)
6990
0
                    window->Size.y = window->SizeFull.y = 0.f;
6991
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6992
0
            }
6993
0
        }
6994
6995
        // SELECT VIEWPORT
6996
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6997
6998
44.8k
        WindowSelectViewport(window);
6999
44.8k
        SetCurrentViewport(window, window->Viewport);
7000
44.8k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7001
44.8k
        SetCurrentWindow(window);
7002
44.8k
        flags = window->Flags;
7003
7004
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7005
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7006
7007
44.8k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7008
435
            window->WindowBorderSize = style.ChildBorderSize;
7009
44.4k
        else
7010
44.4k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7011
44.8k
        window->WindowPadding = style.WindowPadding;
7012
44.8k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7013
253
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7014
7015
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7016
44.8k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7017
44.8k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7018
7019
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7020
        // Those flags will be altered further down in the function depending on more conditions.
7021
44.8k
        bool use_current_size_for_scrollbar_x = window_just_created;
7022
44.8k
        bool use_current_size_for_scrollbar_y = window_just_created;
7023
44.8k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7024
0
            use_current_size_for_scrollbar_x = true;
7025
44.8k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7026
0
            use_current_size_for_scrollbar_y = true;
7027
7028
        // Collapse window by double-clicking on title bar
7029
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7030
44.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7031
44.4k
        {
7032
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7033
44.4k
            ImRect title_bar_rect = window->TitleBarRect();
7034
44.4k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7035
1.09k
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_None)
7036
5
                    window->WantCollapseToggle = true;
7037
44.4k
            if (window->WantCollapseToggle)
7038
5
            {
7039
5
                window->Collapsed = !window->Collapsed;
7040
5
                if (!window->Collapsed)
7041
2
                    use_current_size_for_scrollbar_y = true;
7042
5
                MarkIniSettingsDirty(window);
7043
5
            }
7044
44.4k
        }
7045
435
        else
7046
435
        {
7047
435
            window->Collapsed = false;
7048
435
        }
7049
44.8k
        window->WantCollapseToggle = false;
7050
7051
        // SIZE
7052
7053
        // Outer Decoration Sizes
7054
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7055
44.8k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7056
44.8k
        window->DecoOuterSizeX1 = 0.0f;
7057
44.8k
        window->DecoOuterSizeX2 = 0.0f;
7058
44.8k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7059
44.8k
        window->DecoOuterSizeY2 = 0.0f;
7060
44.8k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7061
7062
        // Calculate auto-fit size, handle automatic resize
7063
44.8k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7064
44.8k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7065
0
        {
7066
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7067
0
            if (!window_size_x_set_by_api)
7068
0
            {
7069
0
                window->SizeFull.x = size_auto_fit.x;
7070
0
                use_current_size_for_scrollbar_x = true;
7071
0
            }
7072
0
            if (!window_size_y_set_by_api)
7073
0
            {
7074
0
                window->SizeFull.y = size_auto_fit.y;
7075
0
                use_current_size_for_scrollbar_y = true;
7076
0
            }
7077
0
        }
7078
44.8k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7079
2
        {
7080
            // Auto-fit may only grow window during the first few frames
7081
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7082
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7083
2
            {
7084
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7085
2
                use_current_size_for_scrollbar_x = true;
7086
2
            }
7087
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7088
2
            {
7089
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7090
2
                use_current_size_for_scrollbar_y = true;
7091
2
            }
7092
2
            if (!window->Collapsed)
7093
2
                MarkIniSettingsDirty(window);
7094
2
        }
7095
7096
        // Apply minimum/maximum window size constraints and final size
7097
44.8k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7098
44.8k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7099
7100
        // POSITION
7101
7102
        // Popup latch its initial position, will position itself when it appears next frame
7103
44.8k
        if (window_just_activated_by_user)
7104
5
        {
7105
5
            window->AutoPosLastDirection = ImGuiDir_None;
7106
5
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7107
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7108
5
        }
7109
7110
        // Position child window
7111
44.8k
        if (flags & ImGuiWindowFlags_ChildWindow)
7112
435
        {
7113
435
            IM_ASSERT(parent_window && parent_window->Active);
7114
435
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7115
435
            parent_window->DC.ChildWindows.push_back(window);
7116
435
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7117
435
                window->Pos = parent_window->DC.CursorPos;
7118
435
        }
7119
7120
44.8k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7121
44.8k
        if (window_pos_with_pivot)
7122
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7123
44.8k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7124
0
            window->Pos = FindBestWindowPosForPopup(window);
7125
44.8k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7126
0
            window->Pos = FindBestWindowPosForPopup(window);
7127
44.8k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7128
0
            window->Pos = FindBestWindowPosForPopup(window);
7129
7130
        // Late create viewport if we don't fit within our current host viewport.
7131
44.8k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7132
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7133
0
            {
7134
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7135
                //ImGuiViewport* old_viewport = window->Viewport;
7136
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7137
7138
                // FIXME-DPI
7139
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7140
0
                SetCurrentViewport(window, window->Viewport);
7141
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7142
0
                SetCurrentWindow(window);
7143
0
            }
7144
7145
44.8k
        if (window->ViewportOwned)
7146
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7147
7148
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7149
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7150
44.8k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7151
44.8k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7152
44.8k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7153
44.8k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7154
7155
        // Clamp position/size so window stays visible within its viewport or monitor
7156
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7157
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7158
44.8k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7159
44.4k
        {
7160
44.4k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7161
44.4k
            {
7162
44.4k
                ClampWindowPos(window, visibility_rect);
7163
44.4k
            }
7164
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7165
0
            {
7166
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7167
0
                {
7168
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7169
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7170
0
                }
7171
0
                else
7172
0
                {
7173
                    // When not moving ensure visible in its monitor
7174
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7175
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7176
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7177
0
                }
7178
0
                visibility_rect.Expand(-visibility_padding);
7179
0
                ClampWindowPos(window, visibility_rect);
7180
0
            }
7181
44.4k
        }
7182
44.8k
        window->Pos = ImTrunc(window->Pos);
7183
7184
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7185
        // Large values tend to lead to variety of artifacts and are not recommended.
7186
44.8k
        if (window->ViewportOwned || window->DockIsActive)
7187
0
            window->WindowRounding = 0.0f;
7188
44.8k
        else
7189
44.8k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7190
7191
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7192
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7193
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7194
7195
        // Apply window focus (new and reactivated windows are moved to front)
7196
44.8k
        bool want_focus = false;
7197
44.8k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7198
5
        {
7199
5
            if (flags & ImGuiWindowFlags_Popup)
7200
0
                want_focus = true;
7201
5
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7202
2
                want_focus = true;
7203
5
        }
7204
7205
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7206
#ifdef IMGUI_ENABLE_TEST_ENGINE
7207
        if (g.TestEngineHookItems)
7208
        {
7209
            IM_ASSERT(window->IDStack.Size == 1);
7210
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7211
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7212
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7213
            window->IDStack.Size = 1;
7214
        }
7215
#endif
7216
7217
        // Decide if we are going to handle borders and resize grips
7218
44.8k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7219
7220
        // Handle manual resize: Resize Grips, Borders, Gamepad
7221
44.8k
        int border_hovered = -1, border_held = -1;
7222
44.8k
        ImU32 resize_grip_col[4] = {};
7223
44.8k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7224
44.8k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7225
44.8k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7226
23.0k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7227
0
            {
7228
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7229
0
                    use_current_size_for_scrollbar_x = true;
7230
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7231
0
                    use_current_size_for_scrollbar_y = true;
7232
0
            }
7233
44.8k
        window->ResizeBorderHovered = (signed char)border_hovered;
7234
44.8k
        window->ResizeBorderHeld = (signed char)border_held;
7235
7236
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7237
44.8k
        if (window->ViewportOwned)
7238
0
        {
7239
0
            if (!window->Viewport->PlatformRequestMove)
7240
0
                window->Viewport->Pos = window->Pos;
7241
0
            if (!window->Viewport->PlatformRequestResize)
7242
0
                window->Viewport->Size = window->Size;
7243
0
            window->Viewport->UpdateWorkRect();
7244
0
            viewport_rect = window->Viewport->GetMainRect();
7245
0
        }
7246
7247
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7248
44.8k
        window->ViewportPos = window->Viewport->Pos;
7249
7250
        // SCROLLBAR VISIBILITY
7251
7252
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7253
44.8k
        if (!window->Collapsed)
7254
23.0k
        {
7255
            // When reading the current size we need to read it after size constraints have been applied.
7256
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7257
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7258
23.0k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7259
23.0k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7260
23.0k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7261
23.0k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7262
23.0k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7263
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7264
23.0k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7265
23.0k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7266
23.0k
            if (window->ScrollbarX && !window->ScrollbarY)
7267
58
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7268
23.0k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7269
7270
            // Amend the partially filled window->DecorationXXX values.
7271
23.0k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7272
23.0k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7273
23.0k
        }
7274
7275
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7276
        // Update various regions. Variables they depend on should be set above in this function.
7277
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7278
7279
        // Outer rectangle
7280
        // Not affected by window border size. Used by:
7281
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7282
        // - Begin() initial clipping rect for drawing window background and borders.
7283
        // - Begin() clipping whole child
7284
44.8k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7285
44.8k
        const ImRect outer_rect = window->Rect();
7286
44.8k
        const ImRect title_bar_rect = window->TitleBarRect();
7287
44.8k
        window->OuterRectClipped = outer_rect;
7288
44.8k
        if (window->DockIsActive)
7289
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7290
44.8k
        window->OuterRectClipped.ClipWith(host_rect);
7291
7292
        // Inner rectangle
7293
        // Not affected by window border size. Used by:
7294
        // - InnerClipRect
7295
        // - ScrollToRectEx()
7296
        // - NavUpdatePageUpPageDown()
7297
        // - Scrollbar()
7298
44.8k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7299
44.8k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7300
44.8k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7301
44.8k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7302
7303
        // Inner clipping rectangle.
7304
        // Will extend a little bit outside the normal work region.
7305
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7306
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7307
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7308
        // Affected by window/frame border size. Used by:
7309
        // - Begin() initial clip rect
7310
44.8k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7311
44.8k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7312
44.8k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7313
44.8k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7314
44.8k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7315
44.8k
        window->InnerClipRect.ClipWithFull(host_rect);
7316
7317
        // Default item width. Make it proportional to window size if window manually resizes
7318
44.8k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7319
44.8k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7320
0
        else
7321
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7322
7323
        // SCROLLING
7324
7325
        // Lock down maximum scrolling
7326
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7327
        // for right/bottom aligned items without creating a scrollbar.
7328
44.8k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7329
44.8k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7330
7331
        // Apply scrolling
7332
44.8k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7333
44.8k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7334
44.8k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7335
7336
        // DRAWING
7337
7338
        // Setup draw list and outer clipping rectangle
7339
44.8k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7340
44.8k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7341
44.8k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7342
7343
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7344
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7345
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7346
44.8k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7347
44.8k
        if (is_undocked_or_docked_visible)
7348
44.8k
        {
7349
44.8k
            bool render_decorations_in_parent = false;
7350
44.8k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7351
435
            {
7352
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7353
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7354
435
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7355
435
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7356
435
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7357
435
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7358
435
                    render_decorations_in_parent = true;
7359
435
            }
7360
44.8k
            if (render_decorations_in_parent)
7361
435
                window->DrawList = parent_window->DrawList;
7362
7363
            // Handle title bar, scrollbar, resize grips and resize borders
7364
44.8k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7365
44.8k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7366
44.8k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7367
7368
44.8k
            if (render_decorations_in_parent)
7369
435
                window->DrawList = &window->DrawListInst;
7370
44.8k
        }
7371
7372
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7373
7374
        // Work rectangle.
7375
        // Affected by window padding and border size. Used by:
7376
        // - Columns() for right-most edge
7377
        // - TreeNode(), CollapsingHeader() for right-most edge
7378
        // - BeginTabBar() for right-most edge
7379
44.8k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7380
44.8k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7381
44.8k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7382
44.8k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7383
44.8k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7384
44.8k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7385
44.8k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7386
44.8k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7387
44.8k
        window->ParentWorkRect = window->WorkRect;
7388
7389
        // [LEGACY] Content Region
7390
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7391
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7392
        // Used by:
7393
        // - Mouse wheel scrolling + many other things
7394
44.8k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7395
44.8k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7396
44.8k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7397
44.8k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7398
7399
        // Setup drawing context
7400
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7401
44.8k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7402
44.8k
        window->DC.GroupOffset.x = 0.0f;
7403
44.8k
        window->DC.ColumnsOffset.x = 0.0f;
7404
7405
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7406
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7407
44.8k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7408
44.8k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7409
44.8k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7410
44.8k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7411
44.8k
        window->DC.CursorPos = window->DC.CursorStartPos;
7412
44.8k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7413
44.8k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7414
44.8k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7415
44.8k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7416
44.8k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7417
44.8k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7418
7419
44.8k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7420
44.8k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7421
44.8k
        window->DC.NavLayersActiveMaskNext = 0x00;
7422
44.8k
        window->DC.NavIsScrollPushableX = true;
7423
44.8k
        window->DC.NavHideHighlightOneFrame = false;
7424
44.8k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7425
7426
44.8k
        window->DC.MenuBarAppending = false;
7427
44.8k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7428
44.8k
        window->DC.TreeDepth = 0;
7429
44.8k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7430
44.8k
        window->DC.ChildWindows.resize(0);
7431
44.8k
        window->DC.StateStorage = &window->StateStorage;
7432
44.8k
        window->DC.CurrentColumns = NULL;
7433
44.8k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7434
44.8k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7435
7436
44.8k
        window->DC.ItemWidth = window->ItemWidthDefault;
7437
44.8k
        window->DC.TextWrapPos = -1.0f; // disabled
7438
44.8k
        window->DC.ItemWidthStack.resize(0);
7439
44.8k
        window->DC.TextWrapPosStack.resize(0);
7440
44.8k
        if (flags & ImGuiWindowFlags_Modal)
7441
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7442
7443
44.8k
        if (window->AutoFitFramesX > 0)
7444
2
            window->AutoFitFramesX--;
7445
44.8k
        if (window->AutoFitFramesY > 0)
7446
2
            window->AutoFitFramesY--;
7447
7448
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7449
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7450
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7451
        // - Position window behind the modal that is not a begin-parent of this window.
7452
44.8k
        if (want_focus)
7453
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7454
44.8k
        if (want_focus && window == g.NavWindow)
7455
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7456
7457
        // Close requested by platform window (apply to all windows in this viewport)
7458
44.8k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7459
0
        {
7460
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7461
0
            *p_open = false;
7462
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7463
0
        }
7464
7465
        // Title bar
7466
44.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7467
44.4k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7468
7469
        // Clear hit test shape every frame
7470
44.8k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7471
7472
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7473
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7474
        // Maybe we can support CTRL+C on every element?
7475
        /*
7476
        //if (g.NavWindow == window && g.ActiveId == 0)
7477
        if (g.ActiveId == window->MoveId)
7478
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7479
                LogToClipboard();
7480
        */
7481
7482
44.8k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7483
44.8k
        {
7484
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7485
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7486
44.8k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7487
6
                BeginDockableDragDropSource(window);
7488
7489
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7490
44.8k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7491
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7492
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7493
0
                        BeginDockableDragDropTarget(window);
7494
44.8k
        }
7495
7496
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7497
        // This is useful to allow creating context menus on title bar only, etc.
7498
44.8k
        if (window->DockIsActive)
7499
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7500
44.8k
        else
7501
44.8k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7502
7503
        // [DEBUG]
7504
44.8k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7505
44.8k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7506
0
            DebugLocateItemResolveWithLastItem();
7507
44.8k
#endif
7508
7509
        // [Test Engine] Register title bar / tab with MoveId.
7510
#ifdef IMGUI_ENABLE_TEST_ENGINE
7511
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7512
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7513
#endif
7514
44.8k
    }
7515
0
    else
7516
0
    {
7517
        // Append
7518
0
        SetCurrentViewport(window, window->Viewport);
7519
0
        SetCurrentWindow(window);
7520
0
    }
7521
7522
44.8k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7523
44.8k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7524
7525
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7526
44.8k
    window->WriteAccessed = false;
7527
44.8k
    window->BeginCount++;
7528
44.8k
    g.NextWindowData.ClearFlags();
7529
7530
    // Update visibility
7531
44.8k
    if (first_begin_of_the_frame)
7532
44.8k
    {
7533
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7534
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7535
        // This is analogous to regular windows being hidden from one frame.
7536
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7537
44.8k
        if (window->DockIsActive && !window->DockTabIsVisible)
7538
0
        {
7539
0
            if (window->LastFrameJustFocused == g.FrameCount)
7540
0
                window->HiddenFramesCannotSkipItems = 1;
7541
0
            else
7542
0
                window->HiddenFramesCanSkipItems = 1;
7543
0
        }
7544
7545
44.8k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7546
435
        {
7547
            // Child window can be out of sight and have "negative" clip windows.
7548
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7549
435
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7550
435
            const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7551
435
            if (!g.LogEnabled && !nav_request)
7552
435
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7553
0
                {
7554
0
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7555
0
                        window->HiddenFramesCannotSkipItems = 1;
7556
0
                    else
7557
0
                        window->HiddenFramesCanSkipItems = 1;
7558
0
                }
7559
7560
            // Hide along with parent or if parent is collapsed
7561
435
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7562
0
                window->HiddenFramesCanSkipItems = 1;
7563
435
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7564
1
                window->HiddenFramesCannotSkipItems = 1;
7565
435
        }
7566
7567
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7568
44.8k
        if (style.Alpha <= 0.0f)
7569
0
            window->HiddenFramesCanSkipItems = 1;
7570
7571
        // Update the Hidden flag
7572
44.8k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7573
44.8k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7574
7575
        // Disable inputs for requested number of frames
7576
44.8k
        if (window->DisableInputsFrames > 0)
7577
0
        {
7578
0
            window->DisableInputsFrames--;
7579
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7580
0
        }
7581
7582
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7583
44.8k
        bool skip_items = false;
7584
44.8k
        if (window->Collapsed || !window->Active || hidden_regular)
7585
21.7k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7586
21.7k
                skip_items = true;
7587
44.8k
        window->SkipItems = skip_items;
7588
7589
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7590
44.8k
        if (window->SkipItems)
7591
21.7k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7592
7593
        // Sanity check: there are two spots which can set Appearing = true
7594
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7595
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7596
44.8k
        if (window->SkipItems && !window->Appearing)
7597
44.8k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7598
44.8k
    }
7599
7600
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7601
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7602
44.8k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7603
44.8k
    if (!window->IsFallbackWindow)
7604
22.6k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7605
0
        {
7606
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7607
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7608
0
            return false;
7609
0
        }
7610
44.8k
#endif
7611
7612
44.8k
    return !window->SkipItems;
7613
44.8k
}
7614
7615
void ImGui::End()
7616
44.8k
{
7617
44.8k
    ImGuiContext& g = *GImGui;
7618
44.8k
    ImGuiWindow* window = g.CurrentWindow;
7619
7620
    // Error checking: verify that user hasn't called End() too many times!
7621
44.8k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7622
0
    {
7623
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7624
0
        return;
7625
0
    }
7626
44.8k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7627
7628
    // Error checking: verify that user doesn't directly call End() on a child window.
7629
44.8k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7630
44.8k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7631
7632
    // Close anything that is open
7633
44.8k
    if (window->DC.CurrentColumns)
7634
0
        EndColumns();
7635
44.8k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7636
44.8k
        PopClipRect();
7637
44.8k
    PopFocusScope();
7638
7639
    // Stop logging
7640
44.8k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7641
44.4k
        LogFinish();
7642
7643
44.8k
    if (window->DC.IsSetPos)
7644
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7645
7646
    // Docking: report contents sizes to parent to allow for auto-resize
7647
44.8k
    if (window->DockNode && window->DockTabIsVisible)
7648
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7649
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7650
7651
    // Pop from window stack
7652
44.8k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7653
44.8k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7654
0
        g.BeginMenuDepth--;
7655
44.8k
    if (window->Flags & ImGuiWindowFlags_Popup)
7656
0
        g.BeginPopupStack.pop_back();
7657
44.8k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7658
44.8k
    g.CurrentWindowStack.pop_back();
7659
44.8k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7660
44.8k
    if (g.CurrentWindow)
7661
22.6k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7662
44.8k
}
7663
7664
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7665
86
{
7666
86
    ImGuiContext& g = *GImGui;
7667
86
    IM_ASSERT(window == window->RootWindow);
7668
7669
86
    const int cur_order = window->FocusOrder;
7670
86
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7671
86
    if (g.WindowsFocusOrder.back() == window)
7672
86
        return;
7673
7674
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7675
0
    for (int n = cur_order; n < new_order; n++)
7676
0
    {
7677
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7678
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7679
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7680
0
    }
7681
0
    g.WindowsFocusOrder[new_order] = window;
7682
0
    window->FocusOrder = (short)new_order;
7683
0
}
7684
7685
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7686
86
{
7687
86
    ImGuiContext& g = *GImGui;
7688
86
    ImGuiWindow* current_front_window = g.Windows.back();
7689
86
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7690
86
        return;
7691
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7692
0
        if (g.Windows[i] == window)
7693
0
        {
7694
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7695
0
            g.Windows[g.Windows.Size - 1] = window;
7696
0
            break;
7697
0
        }
7698
0
}
7699
7700
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7701
0
{
7702
0
    ImGuiContext& g = *GImGui;
7703
0
    if (g.Windows[0] == window)
7704
0
        return;
7705
0
    for (int i = 0; i < g.Windows.Size; i++)
7706
0
        if (g.Windows[i] == window)
7707
0
        {
7708
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7709
0
            g.Windows[0] = window;
7710
0
            break;
7711
0
        }
7712
0
}
7713
7714
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7715
0
{
7716
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7717
0
    ImGuiContext& g = *GImGui;
7718
0
    window = window->RootWindow;
7719
0
    behind_window = behind_window->RootWindow;
7720
0
    int pos_wnd = FindWindowDisplayIndex(window);
7721
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7722
0
    if (pos_wnd < pos_beh)
7723
0
    {
7724
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7725
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7726
0
        g.Windows[pos_beh - 1] = window;
7727
0
    }
7728
0
    else
7729
0
    {
7730
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7731
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7732
0
        g.Windows[pos_beh] = window;
7733
0
    }
7734
0
}
7735
7736
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7737
0
{
7738
0
    ImGuiContext& g = *GImGui;
7739
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7740
0
}
7741
7742
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7743
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7744
5.15k
{
7745
5.15k
    ImGuiContext& g = *GImGui;
7746
7747
    // Modal check?
7748
5.15k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7749
2
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7750
0
        {
7751
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7752
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7753
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7754
0
            return;
7755
0
        }
7756
7757
    // Find last focused child (if any) and focus it instead.
7758
5.15k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7759
0
        window = NavRestoreLastChildNavWindow(window);
7760
7761
    // Apply focus
7762
5.15k
    if (g.NavWindow != window)
7763
151
    {
7764
151
        SetNavWindow(window);
7765
151
        if (window && g.NavDisableMouseHover)
7766
0
            g.NavMousePosDirty = true;
7767
151
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7768
151
        g.NavLayer = ImGuiNavLayer_Main;
7769
151
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7770
151
        g.NavIdIsAlive = false;
7771
151
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7772
7773
        // Close popups if any
7774
151
        ClosePopupsOverWindow(window, false);
7775
151
    }
7776
7777
    // Move the root window to the top of the pile
7778
5.15k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7779
5.15k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7780
5.15k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7781
5.15k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7782
5.15k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7783
7784
    // Steal active widgets. Some of the cases it triggers includes:
7785
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7786
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7787
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7788
5.15k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7789
157
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7790
18
            ClearActiveID();
7791
7792
    // Passing NULL allow to disable keyboard focus
7793
5.15k
    if (!window)
7794
5.07k
        return;
7795
86
    window->LastFrameJustFocused = g.FrameCount;
7796
7797
    // Select in dock node
7798
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7799
    //if (dock_node && dock_node->TabBar)
7800
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7801
7802
    // Bring to front
7803
86
    BringWindowToFocusFront(focus_front_window);
7804
86
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7805
86
        BringWindowToDisplayFront(display_front_window);
7806
86
}
7807
7808
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7809
0
{
7810
0
    ImGuiContext& g = *GImGui;
7811
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7812
0
    if (under_this_window != NULL)
7813
0
    {
7814
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7815
0
        int offset = -1;
7816
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7817
0
        {
7818
0
            under_this_window = under_this_window->ParentWindow;
7819
0
            offset = 0;
7820
0
        }
7821
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7822
0
    }
7823
0
    for (int i = start_idx; i >= 0; i--)
7824
0
    {
7825
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7826
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7827
0
        if (window == ignore_window || !window->WasActive)
7828
0
            continue;
7829
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7830
0
            continue;
7831
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7832
0
        {
7833
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7834
            // This is failing (lagging by one frame) for docked windows.
7835
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7836
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7837
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7838
0
            FocusWindow(window, flags);
7839
0
            return;
7840
0
        }
7841
0
    }
7842
0
    FocusWindow(NULL, flags);
7843
0
}
7844
7845
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7846
void ImGui::SetCurrentFont(ImFont* font)
7847
22.2k
{
7848
22.2k
    ImGuiContext& g = *GImGui;
7849
22.2k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7850
22.2k
    IM_ASSERT(font->Scale > 0.0f);
7851
22.2k
    g.Font = font;
7852
22.2k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7853
22.2k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7854
7855
22.2k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7856
22.2k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7857
22.2k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7858
22.2k
    g.DrawListSharedData.Font = g.Font;
7859
22.2k
    g.DrawListSharedData.FontSize = g.FontSize;
7860
22.2k
}
7861
7862
void ImGui::PushFont(ImFont* font)
7863
0
{
7864
0
    ImGuiContext& g = *GImGui;
7865
0
    if (!font)
7866
0
        font = GetDefaultFont();
7867
0
    SetCurrentFont(font);
7868
0
    g.FontStack.push_back(font);
7869
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7870
0
}
7871
7872
void  ImGui::PopFont()
7873
0
{
7874
0
    ImGuiContext& g = *GImGui;
7875
0
    g.CurrentWindow->DrawList->PopTextureID();
7876
0
    g.FontStack.pop_back();
7877
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7878
0
}
7879
7880
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7881
435
{
7882
435
    ImGuiContext& g = *GImGui;
7883
435
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7884
435
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7885
435
    if (enabled)
7886
0
        item_flags |= option;
7887
435
    else
7888
435
        item_flags &= ~option;
7889
435
    g.CurrentItemFlags = item_flags;
7890
435
    g.ItemFlagsStack.push_back(item_flags);
7891
435
}
7892
7893
void ImGui::PopItemFlag()
7894
435
{
7895
435
    ImGuiContext& g = *GImGui;
7896
435
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7897
435
    g.ItemFlagsStack.pop_back();
7898
435
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7899
435
}
7900
7901
// BeginDisabled()/EndDisabled()
7902
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7903
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7904
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7905
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7906
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7907
void ImGui::BeginDisabled(bool disabled)
7908
0
{
7909
0
    ImGuiContext& g = *GImGui;
7910
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7911
0
    if (!was_disabled && disabled)
7912
0
    {
7913
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7914
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7915
0
    }
7916
0
    if (was_disabled || disabled)
7917
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7918
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7919
0
    g.DisabledStackSize++;
7920
0
}
7921
7922
void ImGui::EndDisabled()
7923
0
{
7924
0
    ImGuiContext& g = *GImGui;
7925
0
    IM_ASSERT(g.DisabledStackSize > 0);
7926
0
    g.DisabledStackSize--;
7927
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7928
    //PopItemFlag();
7929
0
    g.ItemFlagsStack.pop_back();
7930
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7931
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7932
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7933
0
}
7934
7935
void ImGui::PushTabStop(bool tab_stop)
7936
435
{
7937
435
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7938
435
}
7939
7940
void ImGui::PopTabStop()
7941
435
{
7942
435
    PopItemFlag();
7943
435
}
7944
7945
void ImGui::PushButtonRepeat(bool repeat)
7946
0
{
7947
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7948
0
}
7949
7950
void ImGui::PopButtonRepeat()
7951
0
{
7952
0
    PopItemFlag();
7953
0
}
7954
7955
void ImGui::PushTextWrapPos(float wrap_pos_x)
7956
0
{
7957
0
    ImGuiWindow* window = GetCurrentWindow();
7958
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7959
0
    window->DC.TextWrapPos = wrap_pos_x;
7960
0
}
7961
7962
void ImGui::PopTextWrapPos()
7963
0
{
7964
0
    ImGuiWindow* window = GetCurrentWindow();
7965
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7966
0
    window->DC.TextWrapPosStack.pop_back();
7967
0
}
7968
7969
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7970
0
{
7971
0
    ImGuiWindow* last_window = NULL;
7972
0
    while (last_window != window)
7973
0
    {
7974
0
        last_window = window;
7975
0
        window = window->RootWindow;
7976
0
        if (popup_hierarchy)
7977
0
            window = window->RootWindowPopupTree;
7978
0
    if (dock_hierarchy)
7979
0
      window = window->RootWindowDockTree;
7980
0
  }
7981
0
    return window;
7982
0
}
7983
7984
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7985
0
{
7986
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7987
0
    if (window_root == potential_parent)
7988
0
        return true;
7989
0
    while (window != NULL)
7990
0
    {
7991
0
        if (window == potential_parent)
7992
0
            return true;
7993
0
        if (window == window_root) // end of chain
7994
0
            return false;
7995
0
        window = window->ParentWindow;
7996
0
    }
7997
0
    return false;
7998
0
}
7999
8000
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8001
0
{
8002
0
    if (window->RootWindow == potential_parent)
8003
0
        return true;
8004
0
    while (window != NULL)
8005
0
    {
8006
0
        if (window == potential_parent)
8007
0
            return true;
8008
0
        window = window->ParentWindowInBeginStack;
8009
0
    }
8010
0
    return false;
8011
0
}
8012
8013
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8014
0
{
8015
0
    ImGuiContext& g = *GImGui;
8016
8017
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8018
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8019
0
    if (display_layer_delta != 0)
8020
0
        return display_layer_delta > 0;
8021
8022
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8023
0
    {
8024
0
        ImGuiWindow* candidate_window = g.Windows[i];
8025
0
        if (candidate_window == potential_above)
8026
0
            return true;
8027
0
        if (candidate_window == potential_below)
8028
0
            return false;
8029
0
    }
8030
0
    return false;
8031
0
}
8032
8033
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8034
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8035
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8036
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8037
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8038
440
{
8039
440
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8040
8041
440
    ImGuiContext& g = *GImGui;
8042
440
    ImGuiWindow* ref_window = g.HoveredWindow;
8043
440
    ImGuiWindow* cur_window = g.CurrentWindow;
8044
440
    if (ref_window == NULL)
8045
392
        return false;
8046
8047
48
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8048
48
    {
8049
48
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8050
48
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8051
48
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8052
48
        if (flags & ImGuiHoveredFlags_RootWindow)
8053
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8054
8055
48
        bool result;
8056
48
        if (flags & ImGuiHoveredFlags_ChildWindows)
8057
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8058
48
        else
8059
48
            result = (ref_window == cur_window);
8060
48
        if (!result)
8061
47
            return false;
8062
48
    }
8063
8064
1
    if (!IsWindowContentHoverable(ref_window, flags))
8065
0
        return false;
8066
1
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8067
1
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8068
0
            return false;
8069
8070
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8071
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8072
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8073
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8074
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8075
1
    if (flags & ImGuiHoveredFlags_ForTooltip)
8076
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8077
1
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8078
0
        return false;
8079
8080
1
    return true;
8081
1
}
8082
8083
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8084
868
{
8085
868
    ImGuiContext& g = *GImGui;
8086
868
    ImGuiWindow* ref_window = g.NavWindow;
8087
868
    ImGuiWindow* cur_window = g.CurrentWindow;
8088
8089
868
    if (ref_window == NULL)
8090
820
        return false;
8091
48
    if (flags & ImGuiFocusedFlags_AnyWindow)
8092
0
        return true;
8093
8094
48
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8095
48
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8096
48
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8097
48
    if (flags & ImGuiHoveredFlags_RootWindow)
8098
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8099
8100
48
    if (flags & ImGuiHoveredFlags_ChildWindows)
8101
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8102
48
    else
8103
48
        return (ref_window == cur_window);
8104
48
}
8105
8106
ImGuiID ImGui::GetWindowDockID()
8107
0
{
8108
0
    ImGuiContext& g = *GImGui;
8109
0
    return g.CurrentWindow->DockId;
8110
0
}
8111
8112
bool ImGui::IsWindowDocked()
8113
0
{
8114
0
    ImGuiContext& g = *GImGui;
8115
0
    return g.CurrentWindow->DockIsActive;
8116
0
}
8117
8118
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8119
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8120
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8121
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8122
0
{
8123
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8124
0
}
8125
8126
float ImGui::GetWindowWidth()
8127
44
{
8128
44
    ImGuiWindow* window = GImGui->CurrentWindow;
8129
44
    return window->Size.x;
8130
44
}
8131
8132
float ImGui::GetWindowHeight()
8133
44
{
8134
44
    ImGuiWindow* window = GImGui->CurrentWindow;
8135
44
    return window->Size.y;
8136
44
}
8137
8138
ImVec2 ImGui::GetWindowPos()
8139
0
{
8140
0
    ImGuiContext& g = *GImGui;
8141
0
    ImGuiWindow* window = g.CurrentWindow;
8142
0
    return window->Pos;
8143
0
}
8144
8145
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8146
1
{
8147
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8148
1
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8149
0
        return;
8150
8151
1
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8152
1
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8153
1
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8154
8155
    // Set
8156
1
    const ImVec2 old_pos = window->Pos;
8157
1
    window->Pos = ImTrunc(pos);
8158
1
    ImVec2 offset = window->Pos - old_pos;
8159
1
    if (offset.x == 0.0f && offset.y == 0.0f)
8160
0
        return;
8161
1
    MarkIniSettingsDirty(window);
8162
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8163
1
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8164
1
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8165
1
    window->DC.IdealMaxPos += offset;
8166
1
    window->DC.CursorStartPos += offset;
8167
1
}
8168
8169
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8170
0
{
8171
0
    ImGuiWindow* window = GetCurrentWindowRead();
8172
0
    SetWindowPos(window, pos, cond);
8173
0
}
8174
8175
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8176
0
{
8177
0
    if (ImGuiWindow* window = FindWindowByName(name))
8178
0
        SetWindowPos(window, pos, cond);
8179
0
}
8180
8181
ImVec2 ImGui::GetWindowSize()
8182
0
{
8183
0
    ImGuiWindow* window = GetCurrentWindowRead();
8184
0
    return window->Size;
8185
0
}
8186
8187
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8188
22.6k
{
8189
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8190
22.6k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8191
22.2k
        return;
8192
8193
436
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8194
436
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8195
8196
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8197
436
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8198
4
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8199
436
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8200
4
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8201
8202
    // Set
8203
436
    ImVec2 old_size = window->SizeFull;
8204
436
    if (size.x <= 0.0f)
8205
0
        window->AutoFitOnlyGrows = false;
8206
436
    else
8207
436
        window->SizeFull.x = IM_TRUNC(size.x);
8208
436
    if (size.y <= 0.0f)
8209
0
        window->AutoFitOnlyGrows = false;
8210
436
    else
8211
436
        window->SizeFull.y = IM_TRUNC(size.y);
8212
436
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8213
433
        MarkIniSettingsDirty(window);
8214
436
}
8215
8216
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8217
0
{
8218
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8219
0
}
8220
8221
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8222
0
{
8223
0
    if (ImGuiWindow* window = FindWindowByName(name))
8224
0
        SetWindowSize(window, size, cond);
8225
0
}
8226
8227
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8228
0
{
8229
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8230
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8231
0
        return;
8232
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8233
8234
    // Set
8235
0
    window->Collapsed = collapsed;
8236
0
}
8237
8238
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8239
0
{
8240
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8241
0
    window->HitTestHoleSize = ImVec2ih(size);
8242
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8243
0
}
8244
8245
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8246
0
{
8247
0
    window->Hidden = window->SkipItems = true;
8248
0
    window->HiddenFramesCanSkipItems = 1;
8249
0
}
8250
8251
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8252
0
{
8253
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8254
0
}
8255
8256
bool ImGui::IsWindowCollapsed()
8257
0
{
8258
0
    ImGuiWindow* window = GetCurrentWindowRead();
8259
0
    return window->Collapsed;
8260
0
}
8261
8262
bool ImGui::IsWindowAppearing()
8263
0
{
8264
0
    ImGuiWindow* window = GetCurrentWindowRead();
8265
0
    return window->Appearing;
8266
0
}
8267
8268
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8269
0
{
8270
0
    if (ImGuiWindow* window = FindWindowByName(name))
8271
0
        SetWindowCollapsed(window, collapsed, cond);
8272
0
}
8273
8274
void ImGui::SetWindowFocus()
8275
44
{
8276
44
    FocusWindow(GImGui->CurrentWindow);
8277
44
}
8278
8279
void ImGui::SetWindowFocus(const char* name)
8280
0
{
8281
0
    if (name)
8282
0
    {
8283
0
        if (ImGuiWindow* window = FindWindowByName(name))
8284
0
            FocusWindow(window);
8285
0
    }
8286
0
    else
8287
0
    {
8288
0
        FocusWindow(NULL);
8289
0
    }
8290
0
}
8291
8292
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8293
0
{
8294
0
    ImGuiContext& g = *GImGui;
8295
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8296
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8297
0
    g.NextWindowData.PosVal = pos;
8298
0
    g.NextWindowData.PosPivotVal = pivot;
8299
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8300
0
    g.NextWindowData.PosUndock = true;
8301
0
}
8302
8303
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8304
22.6k
{
8305
22.6k
    ImGuiContext& g = *GImGui;
8306
22.6k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8307
22.6k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8308
22.6k
    g.NextWindowData.SizeVal = size;
8309
22.6k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8310
22.6k
}
8311
8312
// For each axis:
8313
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8314
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8315
// - See "Demo->Examples->Constrained-resizing window" for examples.
8316
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8317
0
{
8318
0
    ImGuiContext& g = *GImGui;
8319
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8320
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8321
0
    g.NextWindowData.SizeCallback = custom_callback;
8322
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8323
0
}
8324
8325
// Content size = inner scrollable rectangle, padded with WindowPadding.
8326
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8327
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8328
0
{
8329
0
    ImGuiContext& g = *GImGui;
8330
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8331
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8332
0
}
8333
8334
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8335
0
{
8336
0
    ImGuiContext& g = *GImGui;
8337
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8338
0
    g.NextWindowData.ScrollVal = scroll;
8339
0
}
8340
8341
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8342
0
{
8343
0
    ImGuiContext& g = *GImGui;
8344
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8345
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8346
0
    g.NextWindowData.CollapsedVal = collapsed;
8347
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8348
0
}
8349
8350
void ImGui::SetNextWindowFocus()
8351
0
{
8352
0
    ImGuiContext& g = *GImGui;
8353
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8354
0
}
8355
8356
void ImGui::SetNextWindowBgAlpha(float alpha)
8357
0
{
8358
0
    ImGuiContext& g = *GImGui;
8359
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8360
0
    g.NextWindowData.BgAlphaVal = alpha;
8361
0
}
8362
8363
void ImGui::SetNextWindowViewport(ImGuiID id)
8364
0
{
8365
0
    ImGuiContext& g = *GImGui;
8366
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8367
0
    g.NextWindowData.ViewportId = id;
8368
0
}
8369
8370
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8371
0
{
8372
0
    ImGuiContext& g = *GImGui;
8373
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8374
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8375
0
    g.NextWindowData.DockId = id;
8376
0
}
8377
8378
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8379
0
{
8380
0
    ImGuiContext& g = *GImGui;
8381
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8382
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8383
0
    g.NextWindowData.WindowClass = *window_class;
8384
0
}
8385
8386
ImDrawList* ImGui::GetWindowDrawList()
8387
435
{
8388
435
    ImGuiWindow* window = GetCurrentWindow();
8389
435
    return window->DrawList;
8390
435
}
8391
8392
float ImGui::GetWindowDpiScale()
8393
0
{
8394
0
    ImGuiContext& g = *GImGui;
8395
0
    return g.CurrentDpiScale;
8396
0
}
8397
8398
ImGuiViewport* ImGui::GetWindowViewport()
8399
0
{
8400
0
    ImGuiContext& g = *GImGui;
8401
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8402
0
    return g.CurrentViewport;
8403
0
}
8404
8405
ImFont* ImGui::GetFont()
8406
2.32k
{
8407
2.32k
    return GImGui->Font;
8408
2.32k
}
8409
8410
float ImGui::GetFontSize()
8411
2.32k
{
8412
2.32k
    return GImGui->FontSize;
8413
2.32k
}
8414
8415
ImVec2 ImGui::GetFontTexUvWhitePixel()
8416
0
{
8417
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8418
0
}
8419
8420
void ImGui::SetWindowFontScale(float scale)
8421
0
{
8422
0
    IM_ASSERT(scale > 0.0f);
8423
0
    ImGuiContext& g = *GImGui;
8424
0
    ImGuiWindow* window = GetCurrentWindow();
8425
0
    window->FontWindowScale = scale;
8426
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8427
0
}
8428
8429
void ImGui::PushFocusScope(ImGuiID id)
8430
44.8k
{
8431
44.8k
    ImGuiContext& g = *GImGui;
8432
44.8k
    ImGuiFocusScopeData data;
8433
44.8k
    data.ID = id;
8434
44.8k
    data.WindowID = g.CurrentWindow->ID;
8435
44.8k
    g.FocusScopeStack.push_back(data);
8436
44.8k
    g.CurrentFocusScopeId = id;
8437
44.8k
}
8438
8439
void ImGui::PopFocusScope()
8440
44.8k
{
8441
44.8k
    ImGuiContext& g = *GImGui;
8442
44.8k
    if (g.FocusScopeStack.Size == 0)
8443
0
    {
8444
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8445
0
        return;
8446
0
    }
8447
44.8k
    g.FocusScopeStack.pop_back();
8448
44.8k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8449
44.8k
}
8450
8451
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8452
171
{
8453
171
    ImGuiContext& g = *GImGui;
8454
171
    g.NavFocusScopeId = focus_scope_id;
8455
171
    g.NavFocusRoute.resize(0); // Invalidate
8456
171
    if (focus_scope_id == 0)
8457
84
        return;
8458
87
    IM_ASSERT(g.NavWindow != NULL);
8459
8460
    // Store current path (in reverse order)
8461
87
    if (focus_scope_id == g.CurrentFocusScopeId)
8462
66
    {
8463
        // Top of focus stack contains local focus scopes inside current window
8464
132
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8465
66
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8466
66
    }
8467
21
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8468
21
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8469
0
    else
8470
0
        return;
8471
8472
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8473
131
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8474
44
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8475
87
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8476
87
}
8477
8478
// Focus = move navigation cursor, set scrolling, set focus window.
8479
void ImGui::FocusItem()
8480
0
{
8481
0
    ImGuiContext& g = *GImGui;
8482
0
    ImGuiWindow* window = g.CurrentWindow;
8483
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8484
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8485
0
    {
8486
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8487
0
        return;
8488
0
    }
8489
8490
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8491
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8492
0
    SetNavWindow(window);
8493
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8494
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8495
0
}
8496
8497
void ImGui::ActivateItemByID(ImGuiID id)
8498
0
{
8499
0
    ImGuiContext& g = *GImGui;
8500
0
    g.NavNextActivateId = id;
8501
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8502
0
}
8503
8504
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8505
// But ActivateItem() should function without altering scroll/focus?
8506
void ImGui::SetKeyboardFocusHere(int offset)
8507
0
{
8508
0
    ImGuiContext& g = *GImGui;
8509
0
    ImGuiWindow* window = g.CurrentWindow;
8510
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8511
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8512
8513
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8514
    // When we refactor this function into ActivateItem() we may want to make this an option.
8515
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8516
    // is also automatically dropped in the event g.ActiveId is stolen.
8517
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8518
0
    {
8519
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8520
0
        return;
8521
0
    }
8522
8523
0
    SetNavWindow(window);
8524
8525
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8526
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8527
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8528
0
    if (offset == -1)
8529
0
    {
8530
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8531
0
    }
8532
0
    else
8533
0
    {
8534
0
        g.NavTabbingDir = 1;
8535
0
        g.NavTabbingCounter = offset + 1;
8536
0
    }
8537
0
}
8538
8539
void ImGui::SetItemDefaultFocus()
8540
0
{
8541
0
    ImGuiContext& g = *GImGui;
8542
0
    ImGuiWindow* window = g.CurrentWindow;
8543
0
    if (!window->Appearing)
8544
0
        return;
8545
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8546
0
        return;
8547
8548
0
    g.NavInitRequest = false;
8549
0
    NavApplyItemToResult(&g.NavInitResult);
8550
0
    NavUpdateAnyRequestFlag();
8551
8552
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8553
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8554
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8555
0
}
8556
8557
void ImGui::SetStateStorage(ImGuiStorage* tree)
8558
0
{
8559
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8560
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8561
0
}
8562
8563
ImGuiStorage* ImGui::GetStateStorage()
8564
0
{
8565
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8566
0
    return window->DC.StateStorage;
8567
0
}
8568
8569
bool ImGui::IsRectVisible(const ImVec2& size)
8570
0
{
8571
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8572
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8573
0
}
8574
8575
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8576
0
{
8577
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8578
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8579
0
}
8580
8581
//-----------------------------------------------------------------------------
8582
// [SECTION] ID STACK
8583
//-----------------------------------------------------------------------------
8584
8585
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8586
// it should ideally be flattened at some point but it's been used a lots by widgets.
8587
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8588
46.1k
{
8589
46.1k
    ImGuiID seed = IDStack.back();
8590
46.1k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8591
46.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8592
46.1k
    ImGuiContext& g = *Ctx;
8593
46.1k
    if (g.DebugHookIdInfo == id)
8594
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8595
46.1k
#endif
8596
46.1k
    return id;
8597
46.1k
}
8598
8599
ImGuiID ImGuiWindow::GetID(const void* ptr)
8600
0
{
8601
0
    ImGuiID seed = IDStack.back();
8602
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8603
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8604
0
    ImGuiContext& g = *Ctx;
8605
0
    if (g.DebugHookIdInfo == id)
8606
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8607
0
#endif
8608
0
    return id;
8609
0
}
8610
8611
ImGuiID ImGuiWindow::GetID(int n)
8612
433
{
8613
433
    ImGuiID seed = IDStack.back();
8614
433
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8615
433
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8616
433
    ImGuiContext& g = *Ctx;
8617
433
    if (g.DebugHookIdInfo == id)
8618
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8619
433
#endif
8620
433
    return id;
8621
433
}
8622
8623
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8624
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8625
0
{
8626
0
    ImGuiID seed = IDStack.back();
8627
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8628
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8629
0
    return id;
8630
0
}
8631
8632
void ImGui::PushID(const char* str_id)
8633
433
{
8634
433
    ImGuiContext& g = *GImGui;
8635
433
    ImGuiWindow* window = g.CurrentWindow;
8636
433
    ImGuiID id = window->GetID(str_id);
8637
433
    window->IDStack.push_back(id);
8638
433
}
8639
8640
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8641
0
{
8642
0
    ImGuiContext& g = *GImGui;
8643
0
    ImGuiWindow* window = g.CurrentWindow;
8644
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8645
0
    window->IDStack.push_back(id);
8646
0
}
8647
8648
void ImGui::PushID(const void* ptr_id)
8649
0
{
8650
0
    ImGuiContext& g = *GImGui;
8651
0
    ImGuiWindow* window = g.CurrentWindow;
8652
0
    ImGuiID id = window->GetID(ptr_id);
8653
0
    window->IDStack.push_back(id);
8654
0
}
8655
8656
void ImGui::PushID(int int_id)
8657
0
{
8658
0
    ImGuiContext& g = *GImGui;
8659
0
    ImGuiWindow* window = g.CurrentWindow;
8660
0
    ImGuiID id = window->GetID(int_id);
8661
0
    window->IDStack.push_back(id);
8662
0
}
8663
8664
// Push a given id value ignoring the ID stack as a seed.
8665
void ImGui::PushOverrideID(ImGuiID id)
8666
0
{
8667
0
    ImGuiContext& g = *GImGui;
8668
0
    ImGuiWindow* window = g.CurrentWindow;
8669
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8670
0
    if (g.DebugHookIdInfo == id)
8671
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8672
0
#endif
8673
0
    window->IDStack.push_back(id);
8674
0
}
8675
8676
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8677
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8678
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8679
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8680
0
{
8681
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8682
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8683
0
    ImGuiContext& g = *GImGui;
8684
0
    if (g.DebugHookIdInfo == id)
8685
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8686
0
#endif
8687
0
    return id;
8688
0
}
8689
8690
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8691
0
{
8692
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8693
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8694
0
    ImGuiContext& g = *GImGui;
8695
0
    if (g.DebugHookIdInfo == id)
8696
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8697
0
#endif
8698
0
    return id;
8699
0
}
8700
8701
void ImGui::PopID()
8702
433
{
8703
433
    ImGuiWindow* window = GImGui->CurrentWindow;
8704
433
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8705
433
    window->IDStack.pop_back();
8706
433
}
8707
8708
ImGuiID ImGui::GetID(const char* str_id)
8709
0
{
8710
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8711
0
    return window->GetID(str_id);
8712
0
}
8713
8714
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8715
0
{
8716
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8717
0
    return window->GetID(str_id_begin, str_id_end);
8718
0
}
8719
8720
ImGuiID ImGui::GetID(const void* ptr_id)
8721
0
{
8722
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8723
0
    return window->GetID(ptr_id);
8724
0
}
8725
8726
//-----------------------------------------------------------------------------
8727
// [SECTION] INPUTS
8728
//-----------------------------------------------------------------------------
8729
// - GetKeyData() [Internal]
8730
// - GetKeyIndex() [Internal]
8731
// - GetKeyName()
8732
// - GetKeyChordName() [Internal]
8733
// - CalcTypematicRepeatAmount() [Internal]
8734
// - GetTypematicRepeatRate() [Internal]
8735
// - GetKeyPressedAmount() [Internal]
8736
// - GetKeyMagnitude2d() [Internal]
8737
//-----------------------------------------------------------------------------
8738
// - UpdateKeyRoutingTable() [Internal]
8739
// - GetRoutingIdFromOwnerId() [Internal]
8740
// - GetShortcutRoutingData() [Internal]
8741
// - CalcRoutingScore() [Internal]
8742
// - SetShortcutRouting() [Internal]
8743
// - TestShortcutRouting() [Internal]
8744
//-----------------------------------------------------------------------------
8745
// - IsKeyDown()
8746
// - IsKeyPressed()
8747
// - IsKeyReleased()
8748
//-----------------------------------------------------------------------------
8749
// - IsMouseDown()
8750
// - IsMouseClicked()
8751
// - IsMouseReleased()
8752
// - IsMouseDoubleClicked()
8753
// - GetMouseClickedCount()
8754
// - IsMouseHoveringRect() [Internal]
8755
// - IsMouseDragPastThreshold() [Internal]
8756
// - IsMouseDragging()
8757
// - GetMousePos()
8758
// - SetMousePos() [Internal]
8759
// - GetMousePosOnOpeningCurrentPopup()
8760
// - IsMousePosValid()
8761
// - IsAnyMouseDown()
8762
// - GetMouseDragDelta()
8763
// - ResetMouseDragDelta()
8764
// - GetMouseCursor()
8765
// - SetMouseCursor()
8766
//-----------------------------------------------------------------------------
8767
// - UpdateAliasKey()
8768
// - GetMergedModsFromKeys()
8769
// - UpdateKeyboardInputs()
8770
// - UpdateMouseInputs()
8771
//-----------------------------------------------------------------------------
8772
// - LockWheelingWindow [Internal]
8773
// - FindBestWheelingWindow [Internal]
8774
// - UpdateMouseWheel() [Internal]
8775
//-----------------------------------------------------------------------------
8776
// - SetNextFrameWantCaptureKeyboard()
8777
// - SetNextFrameWantCaptureMouse()
8778
//-----------------------------------------------------------------------------
8779
// - GetInputSourceName() [Internal]
8780
// - DebugPrintInputEvent() [Internal]
8781
// - UpdateInputEvents() [Internal]
8782
//-----------------------------------------------------------------------------
8783
// - GetKeyOwner() [Internal]
8784
// - TestKeyOwner() [Internal]
8785
// - SetKeyOwner() [Internal]
8786
// - SetItemKeyOwner() [Internal]
8787
// - Shortcut() [Internal]
8788
//-----------------------------------------------------------------------------
8789
8790
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiContext* ctx, ImGuiKeyChord key_chord)
8791
88.8k
{
8792
    // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8793
88.8k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8794
88.8k
    if (IsModKey(key))
8795
0
    {
8796
0
        if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8797
0
            key_chord |= ImGuiMod_Ctrl;
8798
0
        if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8799
0
            key_chord |= ImGuiMod_Shift;
8800
0
        if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8801
0
            key_chord |= ImGuiMod_Alt;
8802
0
        if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8803
0
            key_chord |= ImGuiMod_Super;
8804
0
    }
8805
88.8k
    if (key_chord & ImGuiMod_Shortcut)
8806
0
        return (key_chord & ~ImGuiMod_Shortcut) | (ctx->IO.ConfigMacOSXBehaviors ? ImGuiMod_Super : ImGuiMod_Ctrl);
8807
88.8k
    return key_chord;
8808
88.8k
}
8809
8810
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8811
565k
{
8812
565k
    ImGuiContext& g = *ctx;
8813
8814
    // Special storage location for mods
8815
565k
    if (key & ImGuiMod_Mask_)
8816
177k
        key = ConvertSingleModFlagToKey(ctx, key);
8817
8818
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8819
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8820
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8821
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8822
#else
8823
565k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8824
565k
#endif
8825
565k
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8826
565k
}
8827
8828
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8829
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8830
{
8831
    ImGuiContext& g = *GImGui;
8832
    IM_ASSERT(IsNamedKey(key));
8833
    const ImGuiKeyData* key_data = GetKeyData(key);
8834
    return (ImGuiKey)(key_data - g.IO.KeysData);
8835
}
8836
#endif
8837
8838
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8839
static const char* const GKeyNames[] =
8840
{
8841
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8842
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8843
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8844
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8845
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8846
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8847
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8848
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8849
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8850
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8851
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8852
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8853
    "AppBack", "AppForward",
8854
    "GamepadStart", "GamepadBack",
8855
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8856
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8857
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8858
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8859
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8860
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8861
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8862
};
8863
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8864
8865
const char* ImGui::GetKeyName(ImGuiKey key)
8866
0
{
8867
0
    ImGuiContext& g = *GImGui;
8868
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8869
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8870
#else
8871
    if (IsLegacyKey(key))
8872
    {
8873
        if (g.IO.KeyMap[key] == -1)
8874
            return "N/A";
8875
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8876
        key = (ImGuiKey)g.IO.KeyMap[key];
8877
    }
8878
#endif
8879
0
    if (key == ImGuiKey_None)
8880
0
        return "None";
8881
0
    if (key & ImGuiMod_Mask_)
8882
0
        key = ConvertSingleModFlagToKey(&g, key);
8883
0
    if (!IsNamedKey(key))
8884
0
        return "Unknown";
8885
8886
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8887
0
}
8888
8889
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8890
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
8891
0
{
8892
0
    ImGuiContext& g = *GImGui;
8893
0
    key_chord = FixupKeyChord(&g, key_chord);
8894
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
8895
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8896
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8897
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8898
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8899
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8900
0
    return g.TempKeychordName;
8901
0
}
8902
8903
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8904
// t1 = current time (e.g.: g.Time)
8905
// An event is triggered at:
8906
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8907
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8908
0
{
8909
0
    if (t1 == 0.0f)
8910
0
        return 1;
8911
0
    if (t0 >= t1)
8912
0
        return 0;
8913
0
    if (repeat_rate <= 0.0f)
8914
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8915
0
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8916
0
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8917
0
    const int count = count_t1 - count_t0;
8918
0
    return count;
8919
0
}
8920
8921
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8922
6
{
8923
6
    ImGuiContext& g = *GImGui;
8924
6
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8925
6
    {
8926
3
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8927
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8928
3
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8929
6
    }
8930
6
}
8931
8932
// Return value representing the number of presses in the last time period, for the given repeat rate
8933
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8934
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8935
0
{
8936
0
    ImGuiContext& g = *GImGui;
8937
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8938
0
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8939
0
        return 0;
8940
0
    const float t = key_data->DownDuration;
8941
0
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8942
0
}
8943
8944
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8945
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8946
0
{
8947
0
    return ImVec2(
8948
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8949
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8950
0
}
8951
8952
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8953
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8954
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8955
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8956
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8957
22.2k
{
8958
22.2k
    ImGuiContext& g = *GImGui;
8959
22.2k
    rt->EntriesNext.resize(0);
8960
3.44M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8961
3.42M
    {
8962
3.42M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8963
3.42M
        ImGuiKeyRoutingData* routing_entry;
8964
3.42M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8965
0
        {
8966
0
            routing_entry = &rt->Entries[old_routing_idx];
8967
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
8968
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8969
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8970
0
            routing_entry->RoutingNextScore = 255;
8971
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8972
0
                continue;
8973
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8974
8975
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8976
            // This is the result of previous frame's SetShortcutRouting() call.
8977
0
            if (routing_entry->Mods == g.IO.KeyMods)
8978
0
            {
8979
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8980
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8981
0
                {
8982
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8983
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
8984
0
                }
8985
0
            }
8986
0
        }
8987
8988
        // Rewrite linked-list
8989
3.42M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8990
3.42M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8991
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8992
3.42M
    }
8993
22.2k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8994
22.2k
}
8995
8996
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8997
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8998
0
{
8999
0
    ImGuiContext& g = *GImGui;
9000
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9001
0
}
9002
9003
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9004
0
{
9005
    // Majority of shortcuts will be Key + any number of Mods
9006
    // We accept _Single_ mod with ImGuiKey_None.
9007
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9008
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9009
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9010
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9011
0
    ImGuiContext& g = *GImGui;
9012
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9013
0
    ImGuiKeyRoutingData* routing_data;
9014
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9015
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9016
0
    if (key == ImGuiKey_None)
9017
0
        key = ConvertSingleModFlagToKey(&g, mods);
9018
0
    IM_ASSERT(IsNamedKey(key) && (key_chord & ImGuiMod_Shortcut) == 0); // Please call ConvertShortcutMod() in calling function.
9019
9020
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9021
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9022
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9023
0
    {
9024
0
        routing_data = &rt->Entries[idx];
9025
0
        if (routing_data->Mods == mods)
9026
0
            return routing_data;
9027
0
    }
9028
9029
    // Add to linked-list
9030
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9031
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9032
0
    routing_data = &rt->Entries[routing_data_idx];
9033
0
    routing_data->Mods = (ImU16)mods;
9034
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9035
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9036
0
    return routing_data;
9037
0
}
9038
9039
// Current score encoding (lower is highest priority):
9040
//  -   0: ImGuiInputFlags_RouteGlobalHigh
9041
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
9042
//  -   2: ImGuiInputFlags_RouteGlobal
9043
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9044
//  - 254: ImGuiInputFlags_RouteGlobalLow
9045
//  - 255: never route
9046
// 'flags' should include an explicit routing policy
9047
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9048
0
{
9049
0
    if (flags & ImGuiInputFlags_RouteFocused)
9050
0
    {
9051
0
        ImGuiContext& g = *GImGui;
9052
9053
        // ActiveID gets top priority
9054
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9055
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9056
0
            return 1;
9057
9058
        // Score based on distance to focused window (lower is better)
9059
        // Assuming both windows are submitting a routing request,
9060
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9061
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9062
        // Assuming only WindowA is submitting a routing request,
9063
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9064
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9065
0
        if (focus_scope_id == 0)
9066
0
            return 255;
9067
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9068
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9069
0
                return 3 + index_in_focus_path;
9070
9071
0
        return 255;
9072
0
    }
9073
9074
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
9075
0
    if (flags & ImGuiInputFlags_RouteGlobal)
9076
0
        return 2;
9077
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
9078
0
        return 254;
9079
0
    return 0;
9080
0
}
9081
9082
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9083
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9084
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9085
0
{
9086
    // Mimic 'ignore_char_inputs' logic in InputText()
9087
0
    ImGuiContext& g = *GImGui;
9088
9089
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9090
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9091
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Super));
9092
0
    if (ignore_char_inputs)
9093
0
        return false;
9094
9095
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9096
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9097
0
    return g.KeysMayBeCharInput.TestBit(key);
9098
0
}
9099
9100
// Request a desired route for an input chord (key + mods).
9101
// Return true if the route is available this frame.
9102
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9103
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9104
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9105
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9106
44.4k
{
9107
44.4k
    ImGuiContext& g = *GImGui;
9108
44.4k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9109
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9110
44.4k
    else
9111
44.4k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
9112
44.4k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_None);
9113
9114
    // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9115
44.4k
    key_chord = FixupKeyChord(&g, key_chord);
9116
9117
    // [DEBUG] Debug break requested by user
9118
44.4k
    if (g.DebugBreakInShortcutRouting == key_chord)
9119
0
        IM_DEBUG_BREAK();
9120
9121
44.4k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9122
0
        if (g.NavWindow == NULL)
9123
0
            return false;
9124
9125
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9126
44.4k
    if (flags & ImGuiInputFlags_RouteAlways)
9127
44.4k
    {
9128
44.4k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> always\n", GetKeyChordName(key_chord), owner_id, flags);
9129
44.4k
        return true;
9130
44.4k
    }
9131
9132
    // Specific culling when there's an active.
9133
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9134
0
    {
9135
        // Cull shortcuts with no modifiers when it could generate a character.
9136
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9137
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9138
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9139
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9140
0
        if ((flags & ImGuiInputFlags_RouteFocused) && g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9141
0
        {
9142
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> filtered as potential char input\n", GetKeyChordName(key_chord), owner_id, flags);
9143
0
            return false;
9144
0
        }
9145
9146
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9147
0
        if ((flags & ImGuiInputFlags_RouteGlobalHigh) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9148
0
        {
9149
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9150
0
            if (key == ImGuiKey_None)
9151
0
                key = ConvertSingleModFlagToKey(&g, (ImGuiKey)(key_chord & ImGuiMod_Mask_));
9152
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9153
0
                return false;
9154
0
        }
9155
0
    }
9156
9157
    // FIXME-SHORTCUT: A way to configure the location/focus-scope to test would render this more flexible.
9158
0
    const int score = CalcRoutingScore(g.CurrentFocusScopeId, owner_id, flags);
9159
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> score %d\n", GetKeyChordName(key_chord), owner_id, flags, score);
9160
0
    if (score == 255)
9161
0
        return false;
9162
9163
    // Submit routing for NEXT frame (assuming score is sufficient)
9164
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9165
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9166
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9167
0
    if (score < routing_data->RoutingNextScore)
9168
0
    {
9169
0
        routing_data->RoutingNext = owner_id;
9170
0
        routing_data->RoutingNextScore = (ImU8)score;
9171
0
    }
9172
9173
    // Return routing state for CURRENT frame
9174
0
    if (routing_data->RoutingCurr == owner_id)
9175
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9176
0
    return routing_data->RoutingCurr == owner_id;
9177
0
}
9178
9179
// Currently unused by core (but used by tests)
9180
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9181
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9182
0
{
9183
0
    ImGuiContext& g = *GImGui;
9184
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9185
0
    key_chord = FixupKeyChord(&g, key_chord);
9186
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9187
0
    return routing_data->RoutingCurr == routing_id;
9188
0
}
9189
9190
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9191
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9192
bool ImGui::IsKeyDown(ImGuiKey key)
9193
334k
{
9194
334k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9195
334k
}
9196
9197
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9198
334k
{
9199
334k
    const ImGuiKeyData* key_data = GetKeyData(key);
9200
334k
    if (!key_data->Down)
9201
329k
        return false;
9202
5.44k
    if (!TestKeyOwner(key, owner_id))
9203
0
        return false;
9204
5.44k
    return true;
9205
5.44k
}
9206
9207
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9208
70
{
9209
70
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9210
70
}
9211
9212
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9213
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9214
66.7k
{
9215
66.7k
    const ImGuiKeyData* key_data = GetKeyData(key);
9216
66.7k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9217
64.3k
        return false;
9218
2.38k
    const float t = key_data->DownDuration;
9219
2.38k
    if (t < 0.0f)
9220
0
        return false;
9221
2.38k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9222
2.38k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9223
3
        flags |= ImGuiInputFlags_Repeat;
9224
9225
2.38k
    bool pressed = (t == 0.0f);
9226
2.38k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9227
6
    {
9228
6
        float repeat_delay, repeat_rate;
9229
6
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9230
6
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9231
6
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9232
0
        {
9233
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9234
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9235
0
            ImGuiContext& g = *GImGui;
9236
0
            double key_pressed_time = g.Time - t + 0.00001f;
9237
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9238
0
                pressed = false;
9239
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9240
0
                pressed = false;
9241
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9242
0
                pressed = false;
9243
0
        }
9244
6
    }
9245
2.38k
    if (!pressed)
9246
1.33k
        return false;
9247
1.05k
    if (!TestKeyOwner(key, owner_id))
9248
1
        return false;
9249
1.05k
    return true;
9250
1.05k
}
9251
9252
bool ImGui::IsKeyReleased(ImGuiKey key)
9253
1.79k
{
9254
1.79k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9255
1.79k
}
9256
9257
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9258
1.79k
{
9259
1.79k
    const ImGuiKeyData* key_data = GetKeyData(key);
9260
1.79k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9261
1.43k
        return false;
9262
360
    if (!TestKeyOwner(key, owner_id))
9263
0
        return false;
9264
360
    return true;
9265
360
}
9266
9267
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9268
0
{
9269
0
    ImGuiContext& g = *GImGui;
9270
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9271
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9272
0
}
9273
9274
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9275
18
{
9276
18
    ImGuiContext& g = *GImGui;
9277
18
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9278
18
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9279
18
}
9280
9281
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9282
1
{
9283
1
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9284
1
}
9285
9286
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9287
43
{
9288
43
    ImGuiContext& g = *GImGui;
9289
43
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9290
43
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9291
25
        return false;
9292
18
    const float t = g.IO.MouseDownDuration[button];
9293
18
    if (t < 0.0f)
9294
0
        return false;
9295
18
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9296
9297
18
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9298
18
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9299
18
    if (!pressed)
9300
0
        return false;
9301
9302
18
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9303
0
        return false;
9304
9305
18
    return true;
9306
18
}
9307
9308
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9309
0
{
9310
0
    ImGuiContext& g = *GImGui;
9311
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9312
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9313
0
}
9314
9315
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9316
42
{
9317
42
    ImGuiContext& g = *GImGui;
9318
42
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9319
42
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9320
42
}
9321
9322
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9323
1
{
9324
1
    ImGuiContext& g = *GImGui;
9325
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9326
1
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9327
1
}
9328
9329
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9330
0
{
9331
0
    ImGuiContext& g = *GImGui;
9332
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9333
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9334
0
}
9335
9336
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9337
0
{
9338
0
    ImGuiContext& g = *GImGui;
9339
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9340
0
    return g.IO.MouseClickedCount[button];
9341
0
}
9342
9343
// Test if mouse cursor is hovering given rectangle
9344
// NB- Rectangle is clipped by our current clip setting
9345
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9346
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9347
92.6k
{
9348
92.6k
    ImGuiContext& g = *GImGui;
9349
9350
    // Clip
9351
92.6k
    ImRect rect_clipped(r_min, r_max);
9352
92.6k
    if (clip)
9353
47.8k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9354
9355
    // Hit testing, expanded for touch input
9356
92.6k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9357
87.7k
        return false;
9358
4.87k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9359
0
        return false;
9360
4.87k
    return true;
9361
4.87k
}
9362
9363
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9364
// [Internal] This doesn't test if the button is pressed
9365
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9366
24
{
9367
24
    ImGuiContext& g = *GImGui;
9368
24
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9369
24
    if (lock_threshold < 0.0f)
9370
24
        lock_threshold = g.IO.MouseDragThreshold;
9371
24
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9372
24
}
9373
9374
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9375
25
{
9376
25
    ImGuiContext& g = *GImGui;
9377
25
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9378
25
    if (!g.IO.MouseDown[button])
9379
1
        return false;
9380
24
    return IsMouseDragPastThreshold(button, lock_threshold);
9381
25
}
9382
9383
ImVec2 ImGui::GetMousePos()
9384
150
{
9385
150
    ImGuiContext& g = *GImGui;
9386
150
    return g.IO.MousePos;
9387
150
}
9388
9389
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9390
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9391
void ImGui::TeleportMousePos(const ImVec2& pos)
9392
0
{
9393
0
    ImGuiContext& g = *GImGui;
9394
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9395
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9396
0
    g.IO.WantSetMousePos = true;
9397
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9398
0
}
9399
9400
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9401
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9402
0
{
9403
0
    ImGuiContext& g = *GImGui;
9404
0
    if (g.BeginPopupStack.Size > 0)
9405
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9406
0
    return g.IO.MousePos;
9407
0
}
9408
9409
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9410
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9411
58.2k
{
9412
    // The assert is only to silence a false-positive in XCode Static Analysis.
9413
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9414
58.2k
    IM_ASSERT(GImGui != NULL);
9415
58.2k
    const float MOUSE_INVALID = -256000.0f;
9416
58.2k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9417
58.2k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9418
58.2k
}
9419
9420
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9421
bool ImGui::IsAnyMouseDown()
9422
0
{
9423
0
    ImGuiContext& g = *GImGui;
9424
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9425
0
        if (g.IO.MouseDown[n])
9426
0
            return true;
9427
0
    return false;
9428
0
}
9429
9430
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9431
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9432
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9433
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9434
0
{
9435
0
    ImGuiContext& g = *GImGui;
9436
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9437
0
    if (lock_threshold < 0.0f)
9438
0
        lock_threshold = g.IO.MouseDragThreshold;
9439
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9440
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9441
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9442
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9443
0
    return ImVec2(0.0f, 0.0f);
9444
0
}
9445
9446
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9447
0
{
9448
0
    ImGuiContext& g = *GImGui;
9449
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9450
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9451
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9452
0
}
9453
9454
// Get desired mouse cursor shape.
9455
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9456
// updated during the frame, and locked in EndFrame()/Render().
9457
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9458
ImGuiMouseCursor ImGui::GetMouseCursor()
9459
0
{
9460
0
    ImGuiContext& g = *GImGui;
9461
0
    return g.MouseCursor;
9462
0
}
9463
9464
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9465
0
{
9466
0
    ImGuiContext& g = *GImGui;
9467
0
    g.MouseCursor = cursor_type;
9468
0
}
9469
9470
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9471
155k
{
9472
155k
    IM_ASSERT(ImGui::IsAliasKey(key));
9473
155k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9474
155k
    key_data->Down = v;
9475
155k
    key_data->AnalogValue = analog_value;
9476
155k
}
9477
9478
// [Internal] Do not use directly
9479
static ImGuiKeyChord GetMergedModsFromKeys()
9480
44.4k
{
9481
44.4k
    ImGuiKeyChord mods = 0;
9482
44.4k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9483
44.4k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9484
44.4k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9485
44.4k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9486
44.4k
    return mods;
9487
44.4k
}
9488
9489
static void ImGui::UpdateKeyboardInputs()
9490
22.2k
{
9491
22.2k
    ImGuiContext& g = *GImGui;
9492
22.2k
    ImGuiIO& io = g.IO;
9493
9494
    // Import legacy keys or verify they are not used
9495
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9496
    if (io.BackendUsingLegacyKeyArrays == 0)
9497
    {
9498
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9499
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9500
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9501
    }
9502
    else
9503
    {
9504
        if (g.FrameCount == 0)
9505
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9506
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9507
9508
        // Build reverse KeyMap (Named -> Legacy)
9509
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9510
            if (io.KeyMap[n] != -1)
9511
            {
9512
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9513
                io.KeyMap[io.KeyMap[n]] = n;
9514
            }
9515
9516
        // Import legacy keys into new ones
9517
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9518
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9519
            {
9520
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9521
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9522
                io.KeysData[key].Down = io.KeysDown[n];
9523
                if (key != n)
9524
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9525
                io.BackendUsingLegacyKeyArrays = 1;
9526
            }
9527
        if (io.BackendUsingLegacyKeyArrays == 1)
9528
        {
9529
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9530
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9531
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9532
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9533
        }
9534
    }
9535
#endif
9536
9537
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9538
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9539
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9540
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9541
    {
9542
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9543
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9544
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9545
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9546
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9547
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9548
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9549
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9550
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9551
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9552
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9553
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9554
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9555
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9556
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9557
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9558
        #undef NAV_MAP_KEY
9559
    }
9560
#endif
9561
9562
    // Update aliases
9563
133k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9564
111k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9565
22.2k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9566
22.2k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9567
9568
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9569
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9570
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9571
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9572
22.2k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9573
22.2k
    io.KeyMods = GetMergedModsFromKeys();
9574
22.2k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9575
22.2k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9576
22.2k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9577
22.2k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9578
22.2k
    if (prev_key_mods != io.KeyMods)
9579
0
        g.LastKeyModsChangeTime = g.Time;
9580
22.2k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9581
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9582
9583
    // Clear gamepad data if disabled
9584
22.2k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9585
555k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9586
532k
        {
9587
532k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9588
532k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9589
532k
        }
9590
9591
    // Update keys
9592
3.44M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9593
3.42M
    {
9594
3.42M
        ImGuiKeyData* key_data = &io.KeysData[i];
9595
3.42M
        key_data->DownDurationPrev = key_data->DownDuration;
9596
3.42M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9597
3.42M
        if (key_data->DownDuration == 0.0f)
9598
3.90k
        {
9599
3.90k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9600
3.90k
            if (IsKeyboardKey(key))
9601
1.72k
                g.LastKeyboardKeyPressTime = g.Time;
9602
2.18k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9603
0
                g.LastKeyboardKeyPressTime = g.Time;
9604
3.90k
        }
9605
3.42M
    }
9606
9607
    // Update keys/input owner (named keys only): one entry per key
9608
3.44M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9609
3.42M
    {
9610
3.42M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9611
3.42M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9612
3.42M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9613
3.42M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9614
3.40M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9615
3.42M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9616
3.42M
    }
9617
9618
    // Update key routing (for e.g. shortcuts)
9619
22.2k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9620
22.2k
}
9621
9622
static void ImGui::UpdateMouseInputs()
9623
22.2k
{
9624
22.2k
    ImGuiContext& g = *GImGui;
9625
22.2k
    ImGuiIO& io = g.IO;
9626
9627
    // Mouse Wheel swapping flag
9628
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9629
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9630
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9631
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9632
22.2k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9633
9634
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9635
22.2k
    if (IsMousePosValid(&io.MousePos))
9636
6.29k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9637
9638
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9639
22.2k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9640
5.81k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9641
16.3k
    else
9642
16.3k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9643
9644
    // Update stationary timer.
9645
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9646
22.2k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9647
22.2k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9648
22.2k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9649
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9650
9651
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9652
22.2k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9653
1.05k
        g.NavDisableMouseHover = false;
9654
9655
133k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9656
111k
    {
9657
111k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9658
111k
        io.MouseClickedCount[i] = 0; // Will be filled below
9659
111k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9660
111k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9661
111k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9662
111k
        if (io.MouseClicked[i])
9663
1.75k
        {
9664
1.75k
            bool is_repeated_click = false;
9665
1.75k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9666
1.31k
            {
9667
1.31k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9668
1.31k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9669
1.19k
                    is_repeated_click = true;
9670
1.31k
            }
9671
1.75k
            if (is_repeated_click)
9672
1.19k
                io.MouseClickedLastCount[i]++;
9673
561
            else
9674
561
                io.MouseClickedLastCount[i] = 1;
9675
1.75k
            io.MouseClickedTime[i] = g.Time;
9676
1.75k
            io.MouseClickedPos[i] = io.MousePos;
9677
1.75k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9678
1.75k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9679
1.75k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9680
1.75k
        }
9681
109k
        else if (io.MouseDown[i])
9682
5.07k
        {
9683
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9684
5.07k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9685
5.07k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9686
5.07k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9687
5.07k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9688
5.07k
        }
9689
9690
        // We provide io.MouseDoubleClicked[] as a legacy service
9691
111k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9692
9693
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9694
111k
        if (io.MouseClicked[i])
9695
1.75k
            g.NavDisableMouseHover = false;
9696
111k
    }
9697
22.2k
}
9698
9699
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9700
0
{
9701
0
    ImGuiContext& g = *GImGui;
9702
0
    if (window)
9703
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9704
0
    else
9705
0
        g.WheelingWindowReleaseTimer = 0.0f;
9706
0
    if (g.WheelingWindow == window)
9707
0
        return;
9708
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9709
0
    g.WheelingWindow = window;
9710
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9711
0
    if (window == NULL)
9712
0
    {
9713
0
        g.WheelingWindowStartFrame = -1;
9714
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9715
0
    }
9716
0
}
9717
9718
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9719
1
{
9720
    // For each axis, find window in the hierarchy that may want to use scrolling
9721
1
    ImGuiContext& g = *GImGui;
9722
1
    ImGuiWindow* windows[2] = { NULL, NULL };
9723
3
    for (int axis = 0; axis < 2; axis++)
9724
2
        if (wheel[axis] != 0.0f)
9725
2
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9726
0
            {
9727
                // Bubble up into parent window if:
9728
                // - a child window doesn't allow any scrolling.
9729
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9730
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9731
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9732
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9733
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9734
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9735
0
                    break; // select this window
9736
0
            }
9737
1
    if (windows[0] == NULL && windows[1] == NULL)
9738
0
        return NULL;
9739
9740
    // If there's only one window or only one axis then there's no ambiguity
9741
1
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9742
1
        return windows[1] ? windows[1] : windows[0];
9743
9744
    // If candidate are different windows we need to decide which one to prioritize
9745
    // - First frame: only find a winner if one axis is zero.
9746
    // - Subsequent frames: only find a winner when one is more than the other.
9747
0
    if (g.WheelingWindowStartFrame == -1)
9748
0
        g.WheelingWindowStartFrame = g.FrameCount;
9749
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9750
0
    {
9751
0
        g.WheelingWindowWheelRemainder = wheel;
9752
0
        return NULL;
9753
0
    }
9754
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9755
0
}
9756
9757
// Called by NewFrame()
9758
void ImGui::UpdateMouseWheel()
9759
22.2k
{
9760
    // Reset the locked window if we move the mouse or after the timer elapses.
9761
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9762
22.2k
    ImGuiContext& g = *GImGui;
9763
22.2k
    if (g.WheelingWindow != NULL)
9764
0
    {
9765
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9766
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9767
0
            g.WheelingWindowReleaseTimer = 0.0f;
9768
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9769
0
            LockWheelingWindow(NULL, 0.0f);
9770
0
    }
9771
9772
22.2k
    ImVec2 wheel;
9773
22.2k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9774
22.2k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9775
9776
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9777
22.2k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9778
22.2k
    if (!mouse_window || mouse_window->Collapsed)
9779
22.1k
        return;
9780
9781
    // Zoom / Scale window
9782
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9783
49
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9784
0
    {
9785
0
        LockWheelingWindow(mouse_window, wheel.y);
9786
0
        ImGuiWindow* window = mouse_window;
9787
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9788
0
        const float scale = new_font_scale / window->FontWindowScale;
9789
0
        window->FontWindowScale = new_font_scale;
9790
0
        if (window == window->RootWindow)
9791
0
        {
9792
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9793
0
            SetWindowPos(window, window->Pos + offset, 0);
9794
0
            window->Size = ImTrunc(window->Size * scale);
9795
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9796
0
        }
9797
0
        return;
9798
0
    }
9799
49
    if (g.IO.KeyCtrl)
9800
0
        return;
9801
9802
    // Mouse wheel scrolling
9803
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9804
49
    if (g.IO.MouseWheelRequestAxisSwap)
9805
0
        wheel = ImVec2(wheel.y, 0.0f);
9806
9807
    // Maintain a rough average of moving magnitude on both axises
9808
    // FIXME: should by based on wall clock time rather than frame-counter
9809
49
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9810
49
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9811
9812
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9813
49
    wheel += g.WheelingWindowWheelRemainder;
9814
49
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9815
49
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9816
48
        return;
9817
9818
    // Mouse wheel scrolling: find target and apply
9819
    // - don't renew lock if axis doesn't apply on the window.
9820
    // - select a main axis when both axises are being moved.
9821
1
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9822
1
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9823
1
        {
9824
1
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9825
1
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9826
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9827
1
            if (do_scroll[ImGuiAxis_X])
9828
0
            {
9829
0
                LockWheelingWindow(window, wheel.x);
9830
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9831
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9832
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9833
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9834
0
            }
9835
1
            if (do_scroll[ImGuiAxis_Y])
9836
0
            {
9837
0
                LockWheelingWindow(window, wheel.y);
9838
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9839
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9840
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9841
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9842
0
            }
9843
1
        }
9844
1
}
9845
9846
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9847
0
{
9848
0
    ImGuiContext& g = *GImGui;
9849
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9850
0
}
9851
9852
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9853
0
{
9854
0
    ImGuiContext& g = *GImGui;
9855
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9856
0
}
9857
9858
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9859
static const char* GetInputSourceName(ImGuiInputSource source)
9860
0
{
9861
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
9862
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9863
0
    return input_source_names[source];
9864
0
}
9865
static const char* GetMouseSourceName(ImGuiMouseSource source)
9866
0
{
9867
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9868
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9869
0
    return mouse_source_names[source];
9870
0
}
9871
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9872
0
{
9873
0
    ImGuiContext& g = *GImGui;
9874
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9875
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9876
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9877
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9878
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9879
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9880
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9881
0
}
9882
#endif
9883
9884
// Process input queue
9885
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9886
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9887
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9888
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9889
22.2k
{
9890
22.2k
    ImGuiContext& g = *GImGui;
9891
22.2k
    ImGuiIO& io = g.IO;
9892
9893
    // Only trickle chars<>key when working with InputText()
9894
    // FIXME: InputText() could parse event trail?
9895
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9896
22.2k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9897
9898
22.2k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9899
22.2k
    int  mouse_button_changed = 0x00;
9900
22.2k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9901
9902
22.2k
    int event_n = 0;
9903
32.3k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9904
12.8k
    {
9905
12.8k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9906
12.8k
        if (e->Type == ImGuiInputEventType_MousePos)
9907
2.36k
        {
9908
2.36k
            if (g.IO.WantSetMousePos)
9909
0
                continue;
9910
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9911
2.36k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9912
2.36k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9913
408
                break;
9914
1.95k
            io.MousePos = event_pos;
9915
1.95k
            io.MouseSource = e->MousePos.MouseSource;
9916
1.95k
            mouse_moved = true;
9917
1.95k
        }
9918
10.4k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9919
3.80k
        {
9920
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9921
3.80k
            const ImGuiMouseButton button = e->MouseButton.Button;
9922
3.80k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9923
3.80k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9924
1.06k
                break;
9925
2.73k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9926
0
                break;
9927
2.73k
            io.MouseDown[button] = e->MouseButton.Down;
9928
2.73k
            io.MouseSource = e->MouseButton.MouseSource;
9929
2.73k
            mouse_button_changed |= (1 << button);
9930
2.73k
        }
9931
6.64k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9932
625
        {
9933
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9934
625
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9935
167
                break;
9936
458
            io.MouseWheelH += e->MouseWheel.WheelX;
9937
458
            io.MouseWheel += e->MouseWheel.WheelY;
9938
458
            io.MouseSource = e->MouseWheel.MouseSource;
9939
458
            mouse_wheeled = true;
9940
458
        }
9941
6.02k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9942
0
        {
9943
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9944
0
        }
9945
6.02k
        else if (e->Type == ImGuiInputEventType_Key)
9946
3.24k
        {
9947
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9948
3.24k
            ImGuiKey key = e->Key.Key;
9949
3.24k
            IM_ASSERT(key != ImGuiKey_None);
9950
3.24k
            ImGuiKeyData* key_data = GetKeyData(key);
9951
3.24k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9952
3.24k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9953
700
                break;
9954
2.54k
            key_data->Down = e->Key.Down;
9955
2.54k
            key_data->AnalogValue = e->Key.AnalogValue;
9956
2.54k
            key_changed = true;
9957
2.54k
            key_changed_mask.SetBit(key_data_index);
9958
9959
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9960
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9961
            io.KeysDown[key_data_index] = key_data->Down;
9962
            if (io.KeyMap[key_data_index] != -1)
9963
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9964
#endif
9965
2.54k
        }
9966
2.77k
        else if (e->Type == ImGuiInputEventType_Text)
9967
1.84k
        {
9968
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9969
1.84k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9970
282
                break;
9971
1.56k
            unsigned int c = e->Text.Char;
9972
1.56k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9973
1.56k
            if (trickle_interleaved_keys_and_text)
9974
0
                text_inputted = true;
9975
1.56k
        }
9976
931
        else if (e->Type == ImGuiInputEventType_Focus)
9977
931
        {
9978
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9979
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9980
931
            const bool focus_lost = !e->AppFocused.Focused;
9981
931
            io.AppFocusLost = focus_lost;
9982
931
        }
9983
0
        else
9984
0
        {
9985
0
            IM_ASSERT(0 && "Unknown event!");
9986
0
        }
9987
12.8k
    }
9988
9989
    // Record trail (for domain-specific applications wanting to access a precise trail)
9990
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9991
32.3k
    for (int n = 0; n < event_n; n++)
9992
10.1k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9993
9994
    // [DEBUG]
9995
22.2k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9996
22.2k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9997
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9998
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9999
22.2k
#endif
10000
10001
    // Remaining events will be processed on the next frame
10002
22.2k
    if (event_n == g.InputEventsQueue.Size)
10003
19.5k
        g.InputEventsQueue.resize(0);
10004
2.62k
    else
10005
2.62k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10006
10007
    // Clear buttons state when focus is lost
10008
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10009
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10010
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10011
22.2k
    if (g.IO.AppFocusLost)
10012
931
        g.IO.ClearInputKeys();
10013
22.2k
}
10014
10015
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10016
6
{
10017
6
    if (!IsNamedKeyOrModKey(key))
10018
0
        return ImGuiKeyOwner_None;
10019
10020
6
    ImGuiContext& g = *GImGui;
10021
6
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10022
6
    ImGuiID owner_id = owner_data->OwnerCurr;
10023
10024
6
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10025
3
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10026
0
            return ImGuiKeyOwner_None;
10027
10028
6
    return owner_id;
10029
6
}
10030
10031
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10032
// TestKeyOwner(..., None) : (owner == None)
10033
// TestKeyOwner(..., Any)  : no owner test
10034
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10035
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10036
54.8k
{
10037
54.8k
    if (!IsNamedKeyOrModKey(key))
10038
0
        return true;
10039
10040
54.8k
    ImGuiContext& g = *GImGui;
10041
54.8k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10042
13
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10043
1
            return false;
10044
10045
54.8k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10046
54.8k
    if (owner_id == ImGuiKeyOwner_Any)
10047
5.80k
        return (owner_data->LockThisFrame == false);
10048
10049
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10050
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10051
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10052
49.0k
    if (owner_data->OwnerCurr != owner_id)
10053
13
    {
10054
13
        if (owner_data->LockThisFrame)
10055
0
            return false;
10056
13
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
10057
0
            return false;
10058
13
    }
10059
10060
49.0k
    return true;
10061
49.0k
}
10062
10063
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10064
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10065
// - SetKeyOwner(..., None)              : clears owner
10066
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10067
// - SetKeyOwner(..., Any or None, Lock) : set lock
10068
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10069
18
{
10070
18
    ImGuiContext& g = *GImGui;
10071
18
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10072
18
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10073
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10074
10075
18
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10076
18
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10077
10078
    // We cannot lock by default as it would likely break lots of legacy code.
10079
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10080
18
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10081
18
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10082
18
}
10083
10084
// Rarely used helper
10085
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10086
0
{
10087
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10088
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10089
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10090
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10091
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
10092
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10093
0
}
10094
10095
// This is more or less equivalent to:
10096
//   if (IsItemHovered() || IsItemActive())
10097
//       SetKeyOwner(key, GetItemID());
10098
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10099
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10100
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10101
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10102
0
{
10103
0
    ImGuiContext& g = *GImGui;
10104
0
    ImGuiID id = g.LastItemData.ID;
10105
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10106
0
        return;
10107
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10108
0
        flags |= ImGuiInputFlags_CondDefault_;
10109
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10110
0
    {
10111
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10112
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10113
0
    }
10114
0
}
10115
10116
// This is the only public API until we expose owner_id versions of the API as replacements.
10117
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10118
0
{
10119
0
    return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
10120
0
}
10121
10122
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10123
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10124
44.4k
{
10125
44.4k
    ImGuiContext& g = *GImGui;
10126
44.4k
    key_chord = FixupKeyChord(&g, key_chord);
10127
44.4k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10128
44.4k
    if (g.IO.KeyMods != mods)
10129
44.4k
        return false;
10130
10131
    // Special storage location for mods
10132
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10133
0
    if (key == ImGuiKey_None)
10134
0
        key = ConvertSingleModFlagToKey(&g, mods);
10135
0
    if (!IsKeyPressed(key, owner_id, (flags & ImGuiInputFlags_RepeatMask_)))
10136
0
        return false;
10137
0
    return true;
10138
0
}
10139
10140
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord)
10141
0
{
10142
0
    ImGuiContext& g = *GImGui;
10143
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10144
0
    g.NextItemData.Shortcut = key_chord;
10145
0
}
10146
10147
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10148
44.4k
{
10149
    //ImGuiContext& g = *GImGui;
10150
    //IMGUI_DEBUG_LOG("Shortcut(%s, owner_id=0x%08X, flags=%X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), owner_id, flags);
10151
10152
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10153
44.4k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
10154
44.4k
        flags |= ImGuiInputFlags_RouteFocused;
10155
10156
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10157
    // Effectively makes Shortcut() always input-owner aware.
10158
44.4k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_None)
10159
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10160
10161
    // Submit route
10162
44.4k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
10163
0
        return false;
10164
10165
    // Default repeat behavior for Shortcut()
10166
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10167
44.4k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10168
44.4k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10169
10170
44.4k
    if (!IsKeyChordPressed(key_chord, owner_id, flags))
10171
44.4k
        return false;
10172
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10173
0
    return true;
10174
44.4k
}
10175
10176
10177
//-----------------------------------------------------------------------------
10178
// [SECTION] ERROR CHECKING
10179
//-----------------------------------------------------------------------------
10180
10181
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
10182
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10183
// If this triggers you have an issue:
10184
// - Most commonly: mismatched headers and compiled code version.
10185
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
10186
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
10187
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
10188
//   Otherwise it is possible that different compilation units would see different structure layout
10189
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10190
1
{
10191
1
    bool error = false;
10192
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10193
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10194
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10195
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10196
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10197
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10198
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10199
1
    return !error;
10200
1
}
10201
10202
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10203
// This is causing issues and ambiguity and we need to retire that.
10204
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10205
// [Scenario 1]
10206
//  Previously this would make the window content size ~200x200:
10207
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10208
//  Instead, please submit an item:
10209
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10210
//  Alternative:
10211
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10212
// [Scenario 2]
10213
//  For reference this is one of the issue what we aim to fix with this change:
10214
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10215
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10216
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10217
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10218
0
{
10219
0
    ImGuiContext& g = *GImGui;
10220
0
    ImGuiWindow* window = g.CurrentWindow;
10221
0
    IM_ASSERT(window->DC.IsSetPos);
10222
0
    window->DC.IsSetPos = false;
10223
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10224
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10225
0
        return;
10226
0
    if (window->SkipItems)
10227
0
        return;
10228
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10229
#else
10230
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10231
#endif
10232
0
}
10233
10234
static void ImGui::ErrorCheckNewFrameSanityChecks()
10235
22.2k
{
10236
22.2k
    ImGuiContext& g = *GImGui;
10237
10238
    // Check user IM_ASSERT macro
10239
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10240
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10241
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10242
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10243
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10244
22.2k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10245
10246
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10247
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10248
#ifdef __EMSCRIPTEN__
10249
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10250
        g.IO.DeltaTime = 0.00001f;
10251
#endif
10252
10253
    // Check user data
10254
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10255
22.2k
    IM_ASSERT(g.Initialized);
10256
22.2k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10257
22.2k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10258
22.2k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10259
22.2k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10260
22.2k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10261
22.2k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10262
22.2k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10263
22.2k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10264
22.2k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10265
22.2k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10266
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10267
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10268
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10269
10270
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10271
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10272
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10273
#endif
10274
10275
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10276
22.2k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10277
1
        g.IO.ConfigWindowsResizeFromEdges = false;
10278
10279
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10280
22.2k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10281
22.2k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10282
22.2k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10283
22.2k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10284
10285
    // Perform simple checks: multi-viewport and platform windows support
10286
22.2k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10287
1
    {
10288
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10289
0
        {
10290
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10291
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10292
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10293
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10294
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10295
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10296
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10297
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10298
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10299
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10300
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10301
0
        }
10302
1
        else
10303
1
        {
10304
            // Disable feature, our backends do not support it
10305
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10306
1
        }
10307
10308
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10309
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10310
0
        {
10311
0
            IM_UNUSED(mon);
10312
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10313
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10314
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10315
0
        }
10316
1
    }
10317
22.2k
}
10318
10319
static void ImGui::ErrorCheckEndFrameSanityChecks()
10320
22.2k
{
10321
22.2k
    ImGuiContext& g = *GImGui;
10322
10323
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10324
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10325
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10326
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10327
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10328
    // while still correctly asserting on mid-frame key press events.
10329
22.2k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10330
22.2k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10331
22.2k
    IM_UNUSED(key_mods);
10332
10333
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10334
    //ErrorCheckEndFrameRecover();
10335
10336
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10337
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10338
22.2k
    if (g.CurrentWindowStack.Size != 1)
10339
0
    {
10340
0
        if (g.CurrentWindowStack.Size > 1)
10341
0
        {
10342
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10343
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10344
0
            IM_UNUSED(window);
10345
0
            while (g.CurrentWindowStack.Size > 1)
10346
0
                End();
10347
0
        }
10348
0
        else
10349
0
        {
10350
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10351
0
        }
10352
0
    }
10353
10354
22.2k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10355
22.2k
}
10356
10357
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10358
// Must be called during or before EndFrame().
10359
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10360
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10361
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10362
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10363
0
{
10364
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10365
0
    ImGuiContext& g = *GImGui;
10366
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10367
0
    {
10368
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10369
0
        ImGuiWindow* window = g.CurrentWindow;
10370
0
        if (g.CurrentWindowStack.Size == 1)
10371
0
        {
10372
0
            IM_ASSERT(window->IsFallbackWindow);
10373
0
            break;
10374
0
        }
10375
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10376
0
        {
10377
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10378
0
            EndChild();
10379
0
        }
10380
0
        else
10381
0
        {
10382
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10383
0
            End();
10384
0
        }
10385
0
    }
10386
0
}
10387
10388
// Must be called before End()/EndChild()
10389
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10390
0
{
10391
0
    ImGuiContext& g = *GImGui;
10392
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10393
0
    {
10394
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10395
0
        EndTable();
10396
0
    }
10397
10398
0
    ImGuiWindow* window = g.CurrentWindow;
10399
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10400
0
    IM_ASSERT(window != NULL);
10401
0
    while (g.CurrentTabBar != NULL) //-V1044
10402
0
    {
10403
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10404
0
        EndTabBar();
10405
0
    }
10406
0
    while (window->DC.TreeDepth > 0)
10407
0
    {
10408
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10409
0
        TreePop();
10410
0
    }
10411
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10412
0
    {
10413
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10414
0
        EndGroup();
10415
0
    }
10416
0
    while (window->IDStack.Size > 1)
10417
0
    {
10418
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10419
0
        PopID();
10420
0
    }
10421
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10422
0
    {
10423
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10424
0
        EndDisabled();
10425
0
    }
10426
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10427
0
    {
10428
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10429
0
        PopStyleColor();
10430
0
    }
10431
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10432
0
    {
10433
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10434
0
        PopItemFlag();
10435
0
    }
10436
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10437
0
    {
10438
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10439
0
        PopStyleVar();
10440
0
    }
10441
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10442
0
    {
10443
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10444
0
        PopFont();
10445
0
    }
10446
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10447
0
    {
10448
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10449
0
        PopFocusScope();
10450
0
    }
10451
0
}
10452
10453
// Save current stack sizes for later compare
10454
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10455
44.8k
{
10456
44.8k
    ImGuiContext& g = *ctx;
10457
44.8k
    ImGuiWindow* window = g.CurrentWindow;
10458
44.8k
    SizeOfIDStack = (short)window->IDStack.Size;
10459
44.8k
    SizeOfColorStack = (short)g.ColorStack.Size;
10460
44.8k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10461
44.8k
    SizeOfFontStack = (short)g.FontStack.Size;
10462
44.8k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10463
44.8k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10464
44.8k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10465
44.8k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10466
44.8k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10467
44.8k
}
10468
10469
// Compare to detect usage errors
10470
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10471
44.8k
{
10472
44.8k
    ImGuiContext& g = *ctx;
10473
44.8k
    ImGuiWindow* window = g.CurrentWindow;
10474
44.8k
    IM_UNUSED(window);
10475
10476
    // Window stacks
10477
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10478
44.8k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10479
10480
    // Global stacks
10481
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10482
44.8k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10483
44.8k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10484
44.8k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10485
44.8k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10486
44.8k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10487
44.8k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10488
44.8k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10489
44.8k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10490
44.8k
}
10491
10492
//-----------------------------------------------------------------------------
10493
// [SECTION] ITEM SUBMISSION
10494
//-----------------------------------------------------------------------------
10495
// - KeepAliveID()
10496
// - ItemHandleShortcut() [Internal]
10497
// - ItemAdd()
10498
//-----------------------------------------------------------------------------
10499
10500
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10501
void ImGui::KeepAliveID(ImGuiID id)
10502
45.5k
{
10503
45.5k
    ImGuiContext& g = *GImGui;
10504
45.5k
    if (g.ActiveId == id)
10505
22
        g.ActiveIdIsAlive = id;
10506
45.5k
    if (g.ActiveIdPreviousFrame == id)
10507
22
        g.ActiveIdPreviousFrameIsAlive = true;
10508
45.5k
}
10509
10510
static void ItemHandleShortcut(ImGuiID id)
10511
0
{
10512
    // FIXME: Generalize Activation queue?
10513
0
    ImGuiContext& g = *GImGui;
10514
0
    if (ImGui::Shortcut(g.NextItemData.Shortcut, id, ImGuiInputFlags_None) && g.NavActivateId == 0)
10515
0
    {
10516
0
        g.NavActivateId = id; // Will effectively disable clipping.
10517
0
        g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10518
0
        if (g.ActiveId == 0 || g.ActiveId == id)
10519
0
            g.NavActivateDownId = g.NavActivatePressedId = id;
10520
0
        ImGui::NavHighlightActivated(id);
10521
0
    }
10522
0
}
10523
10524
// Declare item bounding box for clipping and interaction.
10525
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10526
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10527
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10528
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10529
45.9k
{
10530
45.9k
    ImGuiContext& g = *GImGui;
10531
45.9k
    ImGuiWindow* window = g.CurrentWindow;
10532
10533
    // Set item data
10534
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10535
45.9k
    g.LastItemData.ID = id;
10536
45.9k
    g.LastItemData.Rect = bb;
10537
45.9k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10538
45.9k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10539
45.9k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10540
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10541
10542
45.9k
    if (id != 0)
10543
45.4k
    {
10544
45.4k
        KeepAliveID(id);
10545
10546
        // Directional navigation processing
10547
        // Runs prior to clipping early-out
10548
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10549
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10550
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10551
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10552
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10553
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10554
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10555
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10556
45.4k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10557
44.7k
        {
10558
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10559
44.7k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10560
44.7k
            if (g.NavId == id || g.NavAnyRequest)
10561
3
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10562
3
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10563
3
                        NavProcessItem();
10564
44.7k
        }
10565
10566
45.4k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10567
0
            ItemHandleShortcut(id);
10568
45.4k
    }
10569
10570
    // Lightweight clear of SetNextItemXXX data.
10571
45.9k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10572
45.9k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10573
10574
#ifdef IMGUI_ENABLE_TEST_ENGINE
10575
    if (id != 0)
10576
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10577
#endif
10578
10579
    // Clipping test
10580
    // (this is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10581
    //const bool is_clipped = IsClippedEx(bb, id);
10582
    //if (is_clipped)
10583
    //    return false;
10584
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10585
45.9k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10586
45.9k
    if (!is_rect_visible)
10587
447
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10588
447
            if (!g.LogEnabled)
10589
447
                return false;
10590
10591
    // [DEBUG]
10592
45.5k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10593
45.5k
    if (id != 0)
10594
45.4k
    {
10595
45.4k
        if (id == g.DebugLocateId)
10596
0
            DebugLocateItemResolveWithLastItem();
10597
10598
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10599
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10600
        // READ THE FAQ: https://dearimgui.com/faq
10601
45.4k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10602
45.4k
    }
10603
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10604
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10605
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10606
45.5k
#endif
10607
10608
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10609
45.5k
    if (is_rect_visible)
10610
45.5k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10611
45.5k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10612
1.13k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10613
45.5k
    return true;
10614
45.9k
}
10615
10616
10617
//-----------------------------------------------------------------------------
10618
// [SECTION] LAYOUT
10619
//-----------------------------------------------------------------------------
10620
// - ItemSize()
10621
// - SameLine()
10622
// - GetCursorScreenPos()
10623
// - SetCursorScreenPos()
10624
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10625
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10626
// - GetCursorStartPos()
10627
// - Indent()
10628
// - Unindent()
10629
// - SetNextItemWidth()
10630
// - PushItemWidth()
10631
// - PushMultiItemsWidths()
10632
// - PopItemWidth()
10633
// - CalcItemWidth()
10634
// - CalcItemSize()
10635
// - GetTextLineHeight()
10636
// - GetTextLineHeightWithSpacing()
10637
// - GetFrameHeight()
10638
// - GetFrameHeightWithSpacing()
10639
// - GetContentRegionMax()
10640
// - GetContentRegionMaxAbs() [Internal]
10641
// - GetContentRegionAvail(),
10642
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10643
// - BeginGroup()
10644
// - EndGroup()
10645
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10646
//-----------------------------------------------------------------------------
10647
10648
// Advance cursor given item size for layout.
10649
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10650
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10651
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10652
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10653
870
{
10654
870
    ImGuiContext& g = *GImGui;
10655
870
    ImGuiWindow* window = g.CurrentWindow;
10656
870
    if (window->SkipItems)
10657
0
        return;
10658
10659
    // We increase the height in this function to accommodate for baseline offset.
10660
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10661
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10662
870
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10663
10664
870
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10665
870
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10666
10667
    // Always align ourselves on pixel boundaries
10668
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10669
870
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10670
870
    window->DC.CursorPosPrevLine.y = line_y1;
10671
870
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10672
870
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10673
870
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10674
870
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10675
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10676
10677
870
    window->DC.PrevLineSize.y = line_height;
10678
870
    window->DC.CurrLineSize.y = 0.0f;
10679
870
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10680
870
    window->DC.CurrLineTextBaseOffset = 0.0f;
10681
870
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10682
10683
    // Horizontal layout mode
10684
870
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10685
0
        SameLine();
10686
870
}
10687
10688
// Gets back to previous line and continue with horizontal layout
10689
//      offset_from_start_x == 0 : follow right after previous item
10690
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10691
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10692
//      spacing_w >= 0           : enforce spacing amount
10693
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10694
0
{
10695
0
    ImGuiContext& g = *GImGui;
10696
0
    ImGuiWindow* window = g.CurrentWindow;
10697
0
    if (window->SkipItems)
10698
0
        return;
10699
10700
0
    if (offset_from_start_x != 0.0f)
10701
0
    {
10702
0
        if (spacing_w < 0.0f)
10703
0
            spacing_w = 0.0f;
10704
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10705
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10706
0
    }
10707
0
    else
10708
0
    {
10709
0
        if (spacing_w < 0.0f)
10710
0
            spacing_w = g.Style.ItemSpacing.x;
10711
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10712
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10713
0
    }
10714
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10715
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10716
0
    window->DC.IsSameLine = true;
10717
0
}
10718
10719
ImVec2 ImGui::GetCursorScreenPos()
10720
585
{
10721
585
    ImGuiWindow* window = GetCurrentWindowRead();
10722
585
    return window->DC.CursorPos;
10723
585
}
10724
10725
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10726
0
{
10727
0
    ImGuiWindow* window = GetCurrentWindow();
10728
0
    window->DC.CursorPos = pos;
10729
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10730
0
    window->DC.IsSetPos = true;
10731
0
}
10732
10733
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10734
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10735
ImVec2 ImGui::GetCursorPos()
10736
0
{
10737
0
    ImGuiWindow* window = GetCurrentWindowRead();
10738
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10739
0
}
10740
10741
float ImGui::GetCursorPosX()
10742
0
{
10743
0
    ImGuiWindow* window = GetCurrentWindowRead();
10744
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10745
0
}
10746
10747
float ImGui::GetCursorPosY()
10748
0
{
10749
0
    ImGuiWindow* window = GetCurrentWindowRead();
10750
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10751
0
}
10752
10753
void ImGui::SetCursorPos(const ImVec2& local_pos)
10754
0
{
10755
0
    ImGuiWindow* window = GetCurrentWindow();
10756
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10757
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10758
0
    window->DC.IsSetPos = true;
10759
0
}
10760
10761
void ImGui::SetCursorPosX(float x)
10762
0
{
10763
0
    ImGuiWindow* window = GetCurrentWindow();
10764
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10765
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10766
0
    window->DC.IsSetPos = true;
10767
0
}
10768
10769
void ImGui::SetCursorPosY(float y)
10770
0
{
10771
0
    ImGuiWindow* window = GetCurrentWindow();
10772
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10773
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10774
0
    window->DC.IsSetPos = true;
10775
0
}
10776
10777
ImVec2 ImGui::GetCursorStartPos()
10778
0
{
10779
0
    ImGuiWindow* window = GetCurrentWindowRead();
10780
0
    return window->DC.CursorStartPos - window->Pos;
10781
0
}
10782
10783
void ImGui::Indent(float indent_w)
10784
0
{
10785
0
    ImGuiContext& g = *GImGui;
10786
0
    ImGuiWindow* window = GetCurrentWindow();
10787
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10788
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10789
0
}
10790
10791
void ImGui::Unindent(float indent_w)
10792
0
{
10793
0
    ImGuiContext& g = *GImGui;
10794
0
    ImGuiWindow* window = GetCurrentWindow();
10795
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10796
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10797
0
}
10798
10799
// Affect large frame+labels widgets only.
10800
void ImGui::SetNextItemWidth(float item_width)
10801
0
{
10802
0
    ImGuiContext& g = *GImGui;
10803
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10804
0
    g.NextItemData.Width = item_width;
10805
0
}
10806
10807
// FIXME: Remove the == 0.0f behavior?
10808
void ImGui::PushItemWidth(float item_width)
10809
0
{
10810
0
    ImGuiContext& g = *GImGui;
10811
0
    ImGuiWindow* window = g.CurrentWindow;
10812
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10813
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10814
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10815
0
}
10816
10817
void ImGui::PushMultiItemsWidths(int components, float w_full)
10818
0
{
10819
0
    ImGuiContext& g = *GImGui;
10820
0
    ImGuiWindow* window = g.CurrentWindow;
10821
0
    IM_ASSERT(components > 0);
10822
0
    const ImGuiStyle& style = g.Style;
10823
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10824
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10825
0
    float prev_split = w_items;
10826
0
    for (int i = components - 1; i > 0; i--)
10827
0
    {
10828
0
        float next_split = IM_TRUNC(w_items * i / components);
10829
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
10830
0
        prev_split = next_split;
10831
0
    }
10832
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
10833
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10834
0
}
10835
10836
void ImGui::PopItemWidth()
10837
0
{
10838
0
    ImGuiWindow* window = GetCurrentWindow();
10839
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10840
0
    window->DC.ItemWidthStack.pop_back();
10841
0
}
10842
10843
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10844
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10845
float ImGui::CalcItemWidth()
10846
0
{
10847
0
    ImGuiContext& g = *GImGui;
10848
0
    ImGuiWindow* window = g.CurrentWindow;
10849
0
    float w;
10850
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10851
0
        w = g.NextItemData.Width;
10852
0
    else
10853
0
        w = window->DC.ItemWidth;
10854
0
    if (w < 0.0f)
10855
0
    {
10856
0
        float region_max_x = GetContentRegionMaxAbs().x;
10857
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10858
0
    }
10859
0
    w = IM_TRUNC(w);
10860
0
    return w;
10861
0
}
10862
10863
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10864
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10865
// Note that only CalcItemWidth() is publicly exposed.
10866
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10867
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10868
435
{
10869
435
    ImGuiContext& g = *GImGui;
10870
435
    ImGuiWindow* window = g.CurrentWindow;
10871
10872
435
    ImVec2 region_max;
10873
435
    if (size.x < 0.0f || size.y < 0.0f)
10874
0
        region_max = GetContentRegionMaxAbs();
10875
10876
435
    if (size.x == 0.0f)
10877
102
        size.x = default_w;
10878
333
    else if (size.x < 0.0f)
10879
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10880
10881
435
    if (size.y == 0.0f)
10882
62
        size.y = default_h;
10883
373
    else if (size.y < 0.0f)
10884
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10885
10886
435
    return size;
10887
435
}
10888
10889
float ImGui::GetTextLineHeight()
10890
0
{
10891
0
    ImGuiContext& g = *GImGui;
10892
0
    return g.FontSize;
10893
0
}
10894
10895
float ImGui::GetTextLineHeightWithSpacing()
10896
435
{
10897
435
    ImGuiContext& g = *GImGui;
10898
435
    return g.FontSize + g.Style.ItemSpacing.y;
10899
435
}
10900
10901
float ImGui::GetFrameHeight()
10902
6
{
10903
6
    ImGuiContext& g = *GImGui;
10904
6
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10905
6
}
10906
10907
float ImGui::GetFrameHeightWithSpacing()
10908
0
{
10909
0
    ImGuiContext& g = *GImGui;
10910
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10911
0
}
10912
10913
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10914
10915
// FIXME: This is in window space (not screen space!).
10916
ImVec2 ImGui::GetContentRegionMax()
10917
0
{
10918
0
    ImGuiContext& g = *GImGui;
10919
0
    ImGuiWindow* window = g.CurrentWindow;
10920
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10921
0
    return mx - window->Pos;
10922
0
}
10923
10924
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10925
ImVec2 ImGui::GetContentRegionMaxAbs()
10926
435
{
10927
435
    ImGuiContext& g = *GImGui;
10928
435
    ImGuiWindow* window = g.CurrentWindow;
10929
435
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10930
435
    return mx;
10931
435
}
10932
10933
ImVec2 ImGui::GetContentRegionAvail()
10934
435
{
10935
435
    ImGuiWindow* window = GImGui->CurrentWindow;
10936
435
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10937
435
}
10938
10939
// In window space (not screen space!)
10940
ImVec2 ImGui::GetWindowContentRegionMin()
10941
0
{
10942
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10943
0
    return window->ContentRegionRect.Min - window->Pos;
10944
0
}
10945
10946
ImVec2 ImGui::GetWindowContentRegionMax()
10947
435
{
10948
435
    ImGuiWindow* window = GImGui->CurrentWindow;
10949
435
    return window->ContentRegionRect.Max - window->Pos;
10950
435
}
10951
10952
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10953
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10954
// FIXME-OPT: Could we safely early out on ->SkipItems?
10955
void ImGui::BeginGroup()
10956
0
{
10957
0
    ImGuiContext& g = *GImGui;
10958
0
    ImGuiWindow* window = g.CurrentWindow;
10959
10960
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10961
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10962
0
    group_data.WindowID = window->ID;
10963
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10964
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10965
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10966
0
    group_data.BackupIndent = window->DC.Indent;
10967
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10968
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10969
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10970
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10971
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10972
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10973
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10974
0
    group_data.EmitItem = true;
10975
10976
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10977
0
    window->DC.Indent = window->DC.GroupOffset;
10978
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10979
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10980
0
    if (g.LogEnabled)
10981
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10982
0
}
10983
10984
void ImGui::EndGroup()
10985
0
{
10986
0
    ImGuiContext& g = *GImGui;
10987
0
    ImGuiWindow* window = g.CurrentWindow;
10988
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10989
10990
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10991
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10992
10993
0
    if (window->DC.IsSetPos)
10994
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10995
10996
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10997
10998
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10999
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11000
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
11001
0
    window->DC.Indent = group_data.BackupIndent;
11002
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11003
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11004
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11005
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11006
0
    if (g.LogEnabled)
11007
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11008
11009
0
    if (!group_data.EmitItem)
11010
0
    {
11011
0
        g.GroupStack.pop_back();
11012
0
        return;
11013
0
    }
11014
11015
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11016
0
    ItemSize(group_bb.GetSize());
11017
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11018
11019
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11020
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11021
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11022
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11023
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11024
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11025
0
    if (group_contains_curr_active_id)
11026
0
        g.LastItemData.ID = g.ActiveId;
11027
0
    else if (group_contains_prev_active_id)
11028
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11029
0
    g.LastItemData.Rect = group_bb;
11030
11031
    // Forward Hovered flag
11032
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11033
0
    if (group_contains_curr_hovered_id)
11034
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11035
11036
    // Forward Edited flag
11037
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11038
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11039
11040
    // Forward Deactivated flag
11041
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11042
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11043
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11044
11045
0
    g.GroupStack.pop_back();
11046
0
    if (g.DebugShowGroupRects)
11047
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11048
0
}
11049
11050
11051
//-----------------------------------------------------------------------------
11052
// [SECTION] SCROLLING
11053
//-----------------------------------------------------------------------------
11054
11055
// Helper to snap on edges when aiming at an item very close to the edge,
11056
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11057
// When we refactor the scrolling API this may be configurable with a flag?
11058
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11059
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11060
0
{
11061
0
    if (target <= snap_min + snap_threshold)
11062
0
        return ImLerp(snap_min, target, center_ratio);
11063
0
    if (target >= snap_max - snap_threshold)
11064
0
        return ImLerp(target, snap_max, center_ratio);
11065
0
    return target;
11066
0
}
11067
11068
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11069
44.8k
{
11070
44.8k
    ImVec2 scroll = window->Scroll;
11071
44.8k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11072
134k
    for (int axis = 0; axis < 2; axis++)
11073
89.7k
    {
11074
89.7k
        if (window->ScrollTarget[axis] < FLT_MAX)
11075
80
        {
11076
80
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11077
80
            float scroll_target = window->ScrollTarget[axis];
11078
80
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11079
0
            {
11080
0
                float snap_min = 0.0f;
11081
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11082
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11083
0
            }
11084
80
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11085
80
        }
11086
89.7k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11087
89.7k
        if (!window->Collapsed && !window->SkipItems)
11088
46.1k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11089
89.7k
    }
11090
44.8k
    return scroll;
11091
44.8k
}
11092
11093
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11094
0
{
11095
0
    ImGuiContext& g = *GImGui;
11096
0
    ImGuiWindow* window = g.CurrentWindow;
11097
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11098
0
}
11099
11100
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11101
0
{
11102
0
    ScrollToRectEx(window, item_rect, flags);
11103
0
}
11104
11105
// Scroll to keep newly navigated item fully into view
11106
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11107
0
{
11108
0
    ImGuiContext& g = *GImGui;
11109
0
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11110
0
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11111
0
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11112
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11113
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11114
11115
    // Check that only one behavior is selected per axis
11116
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11117
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11118
11119
    // Defaults
11120
0
    ImGuiScrollFlags in_flags = flags;
11121
0
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11122
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11123
0
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11124
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11125
11126
0
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11127
0
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11128
0
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11129
0
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11130
11131
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11132
0
    {
11133
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11134
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11135
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11136
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11137
0
    }
11138
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11139
0
    {
11140
0
        if (can_be_fully_visible_x)
11141
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11142
0
        else
11143
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11144
0
    }
11145
11146
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11147
0
    {
11148
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11149
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11150
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11151
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11152
0
    }
11153
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11154
0
    {
11155
0
        if (can_be_fully_visible_y)
11156
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11157
0
        else
11158
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11159
0
    }
11160
11161
0
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11162
0
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11163
11164
    // Also scroll parent window to keep us into view if necessary
11165
0
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11166
0
    {
11167
        // FIXME-SCROLL: May be an option?
11168
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11169
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11170
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11171
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11172
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11173
0
    }
11174
11175
0
    return delta_scroll;
11176
0
}
11177
11178
float ImGui::GetScrollX()
11179
479
{
11180
479
    ImGuiWindow* window = GImGui->CurrentWindow;
11181
479
    return window->Scroll.x;
11182
479
}
11183
11184
float ImGui::GetScrollY()
11185
479
{
11186
479
    ImGuiWindow* window = GImGui->CurrentWindow;
11187
479
    return window->Scroll.y;
11188
479
}
11189
11190
float ImGui::GetScrollMaxX()
11191
0
{
11192
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11193
0
    return window->ScrollMax.x;
11194
0
}
11195
11196
float ImGui::GetScrollMaxY()
11197
0
{
11198
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11199
0
    return window->ScrollMax.y;
11200
0
}
11201
11202
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11203
42
{
11204
42
    window->ScrollTarget.x = scroll_x;
11205
42
    window->ScrollTargetCenterRatio.x = 0.0f;
11206
42
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11207
42
}
11208
11209
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11210
38
{
11211
38
    window->ScrollTarget.y = scroll_y;
11212
38
    window->ScrollTargetCenterRatio.y = 0.0f;
11213
38
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11214
38
}
11215
11216
void ImGui::SetScrollX(float scroll_x)
11217
42
{
11218
42
    ImGuiContext& g = *GImGui;
11219
42
    SetScrollX(g.CurrentWindow, scroll_x);
11220
42
}
11221
11222
void ImGui::SetScrollY(float scroll_y)
11223
38
{
11224
38
    ImGuiContext& g = *GImGui;
11225
38
    SetScrollY(g.CurrentWindow, scroll_y);
11226
38
}
11227
11228
// Note that a local position will vary depending on initial scroll value,
11229
// This is a little bit confusing so bear with us:
11230
//  - local_pos = (absolution_pos - window->Pos)
11231
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11232
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11233
//  - They mostly exist because of legacy API.
11234
// Following the rules above, when trying to work with scrolling code, consider that:
11235
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11236
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11237
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11238
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11239
0
{
11240
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11241
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11242
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11243
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11244
0
}
11245
11246
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11247
0
{
11248
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11249
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11250
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11251
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11252
0
}
11253
11254
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11255
0
{
11256
0
    ImGuiContext& g = *GImGui;
11257
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11258
0
}
11259
11260
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11261
0
{
11262
0
    ImGuiContext& g = *GImGui;
11263
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11264
0
}
11265
11266
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11267
void ImGui::SetScrollHereX(float center_x_ratio)
11268
0
{
11269
0
    ImGuiContext& g = *GImGui;
11270
0
    ImGuiWindow* window = g.CurrentWindow;
11271
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11272
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11273
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11274
11275
    // Tweak: snap on edges when aiming at an item very close to the edge
11276
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11277
0
}
11278
11279
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11280
void ImGui::SetScrollHereY(float center_y_ratio)
11281
0
{
11282
0
    ImGuiContext& g = *GImGui;
11283
0
    ImGuiWindow* window = g.CurrentWindow;
11284
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11285
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11286
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11287
11288
    // Tweak: snap on edges when aiming at an item very close to the edge
11289
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11290
0
}
11291
11292
//-----------------------------------------------------------------------------
11293
// [SECTION] TOOLTIPS
11294
//-----------------------------------------------------------------------------
11295
11296
bool ImGui::BeginTooltip()
11297
0
{
11298
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11299
0
}
11300
11301
bool ImGui::BeginItemTooltip()
11302
0
{
11303
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11304
0
        return false;
11305
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11306
0
}
11307
11308
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11309
0
{
11310
0
    ImGuiContext& g = *GImGui;
11311
11312
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11313
0
    {
11314
        // Drag and Drop tooltips are positioning differently than other tooltips:
11315
        // - offset visibility to increase visibility around mouse.
11316
        // - never clamp within outer viewport boundary.
11317
        // We call SetNextWindowPos() to enforce position and disable clamping.
11318
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11319
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11320
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11321
0
        SetNextWindowPos(tooltip_pos);
11322
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11323
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11324
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11325
0
    }
11326
11327
0
    char window_name[16];
11328
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11329
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11330
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11331
0
            if (window->Active)
11332
0
            {
11333
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11334
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11335
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11336
0
            }
11337
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11338
0
    Begin(window_name, NULL, flags | extra_window_flags);
11339
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11340
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11341
    //if (!ret)
11342
    //    End();
11343
    //return ret;
11344
0
    return true;
11345
0
}
11346
11347
void ImGui::EndTooltip()
11348
0
{
11349
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11350
0
    End();
11351
0
}
11352
11353
void ImGui::SetTooltip(const char* fmt, ...)
11354
0
{
11355
0
    va_list args;
11356
0
    va_start(args, fmt);
11357
0
    SetTooltipV(fmt, args);
11358
0
    va_end(args);
11359
0
}
11360
11361
void ImGui::SetTooltipV(const char* fmt, va_list args)
11362
0
{
11363
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11364
0
        return;
11365
0
    TextV(fmt, args);
11366
0
    EndTooltip();
11367
0
}
11368
11369
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11370
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11371
void ImGui::SetItemTooltip(const char* fmt, ...)
11372
0
{
11373
0
    va_list args;
11374
0
    va_start(args, fmt);
11375
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11376
0
        SetTooltipV(fmt, args);
11377
0
    va_end(args);
11378
0
}
11379
11380
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11381
0
{
11382
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11383
0
        SetTooltipV(fmt, args);
11384
0
}
11385
11386
11387
//-----------------------------------------------------------------------------
11388
// [SECTION] POPUPS
11389
//-----------------------------------------------------------------------------
11390
11391
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11392
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11393
0
{
11394
0
    ImGuiContext& g = *GImGui;
11395
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11396
0
    {
11397
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11398
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11399
0
        IM_ASSERT(id == 0);
11400
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11401
0
            return g.OpenPopupStack.Size > 0;
11402
0
        else
11403
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11404
0
    }
11405
0
    else
11406
0
    {
11407
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11408
0
        {
11409
            // Return true if the popup is open anywhere in the popup stack
11410
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11411
0
                if (popup_data.PopupId == id)
11412
0
                    return true;
11413
0
            return false;
11414
0
        }
11415
0
        else
11416
0
        {
11417
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11418
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11419
0
        }
11420
0
    }
11421
0
}
11422
11423
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11424
0
{
11425
0
    ImGuiContext& g = *GImGui;
11426
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11427
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11428
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11429
0
    return IsPopupOpen(id, popup_flags);
11430
0
}
11431
11432
// Also see FindBlockingModal(NULL)
11433
ImGuiWindow* ImGui::GetTopMostPopupModal()
11434
66.7k
{
11435
66.7k
    ImGuiContext& g = *GImGui;
11436
66.7k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11437
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11438
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11439
0
                return popup;
11440
66.7k
    return NULL;
11441
66.7k
}
11442
11443
// See Demo->Stacked Modal to confirm what this is for.
11444
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11445
22.2k
{
11446
22.2k
    ImGuiContext& g = *GImGui;
11447
22.2k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11448
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11449
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11450
0
                return popup;
11451
22.2k
    return NULL;
11452
22.2k
}
11453
11454
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11455
0
{
11456
0
    ImGuiContext& g = *GImGui;
11457
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11458
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11459
0
    OpenPopupEx(id, popup_flags);
11460
0
}
11461
11462
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11463
0
{
11464
0
    OpenPopupEx(id, popup_flags);
11465
0
}
11466
11467
// Mark popup as open (toggle toward open state).
11468
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11469
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11470
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11471
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11472
0
{
11473
0
    ImGuiContext& g = *GImGui;
11474
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11475
0
    const int current_stack_size = g.BeginPopupStack.Size;
11476
11477
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11478
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11479
0
            return;
11480
11481
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11482
0
    popup_ref.PopupId = id;
11483
0
    popup_ref.Window = NULL;
11484
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11485
0
    popup_ref.OpenFrameCount = g.FrameCount;
11486
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11487
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11488
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11489
11490
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11491
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11492
0
    {
11493
0
        g.OpenPopupStack.push_back(popup_ref);
11494
0
    }
11495
0
    else
11496
0
    {
11497
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11498
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11499
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11500
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11501
0
        bool keep_existing = false;
11502
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11503
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11504
0
                keep_existing = true;
11505
0
        if (keep_existing)
11506
0
        {
11507
            // No reopen
11508
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11509
0
        }
11510
0
        else
11511
0
        {
11512
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11513
0
            ClosePopupToLevel(current_stack_size, true);
11514
0
            g.OpenPopupStack.push_back(popup_ref);
11515
0
        }
11516
11517
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11518
        // This is equivalent to what ClosePopupToLevel() does.
11519
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11520
        //    FocusWindow(parent_window);
11521
0
    }
11522
0
}
11523
11524
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11525
// This function closes any popups that are over 'ref_window'.
11526
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11527
322
{
11528
322
    ImGuiContext& g = *GImGui;
11529
322
    if (g.OpenPopupStack.Size == 0)
11530
322
        return;
11531
11532
    // Don't close our own child popup windows.
11533
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11534
0
    int popup_count_to_keep = 0;
11535
0
    if (ref_window)
11536
0
    {
11537
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11538
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11539
0
        {
11540
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11541
0
            if (!popup.Window)
11542
0
                continue;
11543
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11544
11545
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11546
            // - Clicking/Focusing Window2 won't close Popup1:
11547
            //     Window -> Popup1 -> Window2(Ref)
11548
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11549
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11550
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11551
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11552
            // We step through every popup from bottom to top to validate their position relative to reference window.
11553
0
            bool ref_window_is_descendent_of_popup = false;
11554
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11555
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11556
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11557
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11558
0
                    {
11559
0
                        ref_window_is_descendent_of_popup = true;
11560
0
                        break;
11561
0
                    }
11562
0
            if (!ref_window_is_descendent_of_popup)
11563
0
                break;
11564
0
        }
11565
0
    }
11566
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11567
0
    {
11568
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11569
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11570
0
    }
11571
0
}
11572
11573
void ImGui::ClosePopupsExceptModals()
11574
0
{
11575
0
    ImGuiContext& g = *GImGui;
11576
11577
0
    int popup_count_to_keep;
11578
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11579
0
    {
11580
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11581
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11582
0
            break;
11583
0
    }
11584
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11585
0
        ClosePopupToLevel(popup_count_to_keep, true);
11586
0
}
11587
11588
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11589
0
{
11590
0
    ImGuiContext& g = *GImGui;
11591
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11592
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11593
11594
    // Trim open popup stack
11595
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11596
0
    g.OpenPopupStack.resize(remaining);
11597
11598
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11599
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11600
0
    {
11601
0
        ImGuiWindow* popup_window = prev_popup.Window;
11602
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11603
0
        if (focus_window && !focus_window->WasActive)
11604
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11605
0
        else
11606
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11607
0
    }
11608
0
}
11609
11610
// Close the popup we have begin-ed into.
11611
void ImGui::CloseCurrentPopup()
11612
0
{
11613
0
    ImGuiContext& g = *GImGui;
11614
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11615
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11616
0
        return;
11617
11618
    // Closing a menu closes its top-most parent popup (unless a modal)
11619
0
    while (popup_idx > 0)
11620
0
    {
11621
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11622
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11623
0
        bool close_parent = false;
11624
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11625
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11626
0
                close_parent = true;
11627
0
        if (!close_parent)
11628
0
            break;
11629
0
        popup_idx--;
11630
0
    }
11631
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11632
0
    ClosePopupToLevel(popup_idx, true);
11633
11634
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11635
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11636
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11637
0
    if (ImGuiWindow* window = g.NavWindow)
11638
0
        window->DC.NavHideHighlightOneFrame = true;
11639
0
}
11640
11641
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11642
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11643
0
{
11644
0
    ImGuiContext& g = *GImGui;
11645
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11646
0
    {
11647
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11648
0
        return false;
11649
0
    }
11650
11651
0
    char name[20];
11652
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11653
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11654
0
    else
11655
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11656
11657
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11658
0
    bool is_open = Begin(name, NULL, flags);
11659
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11660
0
        EndPopup();
11661
11662
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11663
11664
0
    return is_open;
11665
0
}
11666
11667
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11668
0
{
11669
0
    ImGuiContext& g = *GImGui;
11670
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11671
0
    {
11672
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11673
0
        return false;
11674
0
    }
11675
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11676
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11677
0
    return BeginPopupEx(id, flags);
11678
0
}
11679
11680
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11681
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11682
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11683
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11684
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11685
0
{
11686
0
    ImGuiContext& g = *GImGui;
11687
0
    ImGuiWindow* window = g.CurrentWindow;
11688
0
    const ImGuiID id = window->GetID(name);
11689
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11690
0
    {
11691
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11692
0
        if (p_open && *p_open)
11693
0
            *p_open = false;
11694
0
        return false;
11695
0
    }
11696
11697
    // Center modal windows by default for increased visibility
11698
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11699
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11700
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11701
0
    {
11702
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11703
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11704
0
    }
11705
11706
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11707
0
    const bool is_open = Begin(name, p_open, flags);
11708
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11709
0
    {
11710
0
        EndPopup();
11711
0
        if (is_open)
11712
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11713
0
        return false;
11714
0
    }
11715
0
    return is_open;
11716
0
}
11717
11718
void ImGui::EndPopup()
11719
0
{
11720
0
    ImGuiContext& g = *GImGui;
11721
0
    ImGuiWindow* window = g.CurrentWindow;
11722
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11723
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11724
11725
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11726
0
    if (g.NavWindow == window)
11727
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11728
11729
    // Child-popups don't need to be laid out
11730
0
    IM_ASSERT(g.WithinEndChild == false);
11731
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11732
0
        g.WithinEndChild = true;
11733
0
    End();
11734
0
    g.WithinEndChild = false;
11735
0
}
11736
11737
// Helper to open a popup if mouse button is released over the item
11738
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11739
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11740
0
{
11741
0
    ImGuiContext& g = *GImGui;
11742
0
    ImGuiWindow* window = g.CurrentWindow;
11743
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11744
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11745
0
    {
11746
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11747
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11748
0
        OpenPopupEx(id, popup_flags);
11749
0
    }
11750
0
}
11751
11752
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11753
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11754
// - To create a popup with a specific identifier, pass it in str_id.
11755
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11756
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11757
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11758
//   This is essentially the same as:
11759
//       id = str_id ? GetID(str_id) : GetItemID();
11760
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11761
//       return BeginPopup(id);
11762
//   Which is essentially the same as:
11763
//       id = str_id ? GetID(str_id) : GetItemID();
11764
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11765
//           OpenPopup(id);
11766
//       return BeginPopup(id);
11767
//   The main difference being that this is tweaked to avoid computing the ID twice.
11768
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11769
0
{
11770
0
    ImGuiContext& g = *GImGui;
11771
0
    ImGuiWindow* window = g.CurrentWindow;
11772
0
    if (window->SkipItems)
11773
0
        return false;
11774
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11775
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11776
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11777
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11778
0
        OpenPopupEx(id, popup_flags);
11779
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11780
0
}
11781
11782
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11783
0
{
11784
0
    ImGuiContext& g = *GImGui;
11785
0
    ImGuiWindow* window = g.CurrentWindow;
11786
0
    if (!str_id)
11787
0
        str_id = "window_context";
11788
0
    ImGuiID id = window->GetID(str_id);
11789
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11790
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11791
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11792
0
            OpenPopupEx(id, popup_flags);
11793
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11794
0
}
11795
11796
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11797
0
{
11798
0
    ImGuiContext& g = *GImGui;
11799
0
    ImGuiWindow* window = g.CurrentWindow;
11800
0
    if (!str_id)
11801
0
        str_id = "void_context";
11802
0
    ImGuiID id = window->GetID(str_id);
11803
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11804
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11805
0
        if (GetTopMostPopupModal() == NULL)
11806
0
            OpenPopupEx(id, popup_flags);
11807
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11808
0
}
11809
11810
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11811
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11812
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11813
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11814
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11815
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11816
0
{
11817
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11818
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11819
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11820
11821
    // Combo Box policy (we want a connecting edge)
11822
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11823
0
    {
11824
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11825
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11826
0
        {
11827
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11828
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11829
0
                continue;
11830
0
            ImVec2 pos;
11831
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11832
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11833
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11834
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11835
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11836
0
                continue;
11837
0
            *last_dir = dir;
11838
0
            return pos;
11839
0
        }
11840
0
    }
11841
11842
    // Tooltip and Default popup policy
11843
    // (Always first try the direction we used on the last frame, if any)
11844
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11845
0
    {
11846
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11847
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11848
0
        {
11849
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11850
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11851
0
                continue;
11852
11853
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11854
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11855
11856
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11857
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11858
0
                continue;
11859
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11860
0
                continue;
11861
11862
0
            ImVec2 pos;
11863
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11864
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11865
11866
            // Clamp top-left corner of popup
11867
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11868
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11869
11870
0
            *last_dir = dir;
11871
0
            return pos;
11872
0
        }
11873
0
    }
11874
11875
    // Fallback when not enough room:
11876
0
    *last_dir = ImGuiDir_None;
11877
11878
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11879
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11880
0
        return ref_pos + ImVec2(2, 2);
11881
11882
    // Otherwise try to keep within display
11883
0
    ImVec2 pos = ref_pos;
11884
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11885
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11886
0
    return pos;
11887
0
}
11888
11889
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11890
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11891
0
{
11892
0
    ImGuiContext& g = *GImGui;
11893
0
    ImRect r_screen;
11894
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11895
0
    {
11896
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11897
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11898
0
        r_screen.Min = monitor.WorkPos;
11899
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11900
0
    }
11901
0
    else
11902
0
    {
11903
        // Use the full viewport area (not work area) for popups
11904
0
        r_screen = window->Viewport->GetMainRect();
11905
0
    }
11906
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11907
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11908
0
    return r_screen;
11909
0
}
11910
11911
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11912
0
{
11913
0
    ImGuiContext& g = *GImGui;
11914
11915
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11916
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11917
0
    {
11918
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11919
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11920
0
        ImGuiWindow* parent_window = window->ParentWindow;
11921
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11922
0
        ImRect r_avoid;
11923
0
        if (parent_window->DC.MenuBarAppending)
11924
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11925
0
        else
11926
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11927
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11928
0
    }
11929
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11930
0
    {
11931
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11932
0
    }
11933
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11934
0
    {
11935
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11936
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11937
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11938
0
        IM_ASSERT(g.CurrentWindow == window);
11939
0
        const float scale = g.Style.MouseCursorScale;
11940
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11941
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11942
0
        ImRect r_avoid;
11943
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11944
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11945
0
        else
11946
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11947
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11948
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11949
0
    }
11950
0
    IM_ASSERT(0);
11951
0
    return window->Pos;
11952
0
}
11953
11954
//-----------------------------------------------------------------------------
11955
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11956
//-----------------------------------------------------------------------------
11957
11958
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11959
// In our terminology those should be interchangeable, yet right now this is super confusing.
11960
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11961
11962
void ImGui::SetNavWindow(ImGuiWindow* window)
11963
169
{
11964
169
    ImGuiContext& g = *GImGui;
11965
169
    if (g.NavWindow != window)
11966
169
    {
11967
169
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11968
169
        g.NavWindow = window;
11969
169
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11970
169
    }
11971
169
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11972
169
    NavUpdateAnyRequestFlag();
11973
169
}
11974
11975
void ImGui::NavHighlightActivated(ImGuiID id)
11976
0
{
11977
0
    ImGuiContext& g = *GImGui;
11978
0
    g.NavHighlightActivatedId = id;
11979
0
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
11980
0
}
11981
11982
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11983
40
{
11984
40
    ImGuiContext& g = *GImGui;
11985
40
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11986
40
}
11987
11988
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11989
2
{
11990
2
    ImGuiContext& g = *GImGui;
11991
2
    IM_ASSERT(g.NavWindow != NULL);
11992
2
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11993
2
    g.NavId = id;
11994
2
    g.NavLayer = nav_layer;
11995
2
    SetNavFocusScope(focus_scope_id);
11996
2
    g.NavWindow->NavLastIds[nav_layer] = id;
11997
2
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11998
11999
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12000
2
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12001
2
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12002
2
}
12003
12004
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12005
18
{
12006
18
    ImGuiContext& g = *GImGui;
12007
18
    IM_ASSERT(id != 0);
12008
12009
18
    if (g.NavWindow != window)
12010
18
       SetNavWindow(window);
12011
12012
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12013
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12014
18
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12015
18
    g.NavId = id;
12016
18
    g.NavLayer = nav_layer;
12017
18
    SetNavFocusScope(g.CurrentFocusScopeId);
12018
18
    window->NavLastIds[nav_layer] = id;
12019
18
    if (g.LastItemData.ID == id)
12020
18
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12021
12022
18
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12023
0
        g.NavDisableMouseHover = true;
12024
18
    else
12025
18
        g.NavDisableHighlight = true;
12026
12027
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12028
18
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12029
18
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12030
18
}
12031
12032
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12033
0
{
12034
0
    if (ImFabs(dx) > ImFabs(dy))
12035
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12036
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12037
0
}
12038
12039
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12040
0
{
12041
0
    if (cand_max < curr_min)
12042
0
        return cand_max - curr_min;
12043
0
    if (curr_max < cand_min)
12044
0
        return cand_min - curr_max;
12045
0
    return 0.0f;
12046
0
}
12047
12048
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12049
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12050
0
{
12051
0
    ImGuiContext& g = *GImGui;
12052
0
    ImGuiWindow* window = g.CurrentWindow;
12053
0
    if (g.NavLayer != window->DC.NavLayerCurrent)
12054
0
        return false;
12055
12056
    // FIXME: Those are not good variables names
12057
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12058
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12059
0
    g.NavScoringDebugCount++;
12060
12061
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12062
0
    if (window->ParentWindow == g.NavWindow)
12063
0
    {
12064
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
12065
0
        if (!window->ClipRect.Overlaps(cand))
12066
0
            return false;
12067
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12068
0
    }
12069
12070
    // Compute distance between boxes
12071
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12072
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12073
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12074
0
    if (dby != 0.0f && dbx != 0.0f)
12075
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12076
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12077
12078
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12079
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12080
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12081
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12082
12083
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12084
0
    ImGuiDir quadrant;
12085
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12086
0
    if (dbx != 0.0f || dby != 0.0f)
12087
0
    {
12088
        // For non-overlapping boxes, use distance between boxes
12089
0
        dax = dbx;
12090
0
        day = dby;
12091
0
        dist_axial = dist_box;
12092
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12093
0
    }
12094
0
    else if (dcx != 0.0f || dcy != 0.0f)
12095
0
    {
12096
        // For overlapping boxes with different centers, use distance between centers
12097
0
        dax = dcx;
12098
0
        day = dcy;
12099
0
        dist_axial = dist_center;
12100
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12101
0
    }
12102
0
    else
12103
0
    {
12104
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12105
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12106
0
    }
12107
12108
0
    const ImGuiDir move_dir = g.NavMoveDir;
12109
#if IMGUI_DEBUG_NAV_SCORING
12110
    char buf[200];
12111
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12112
    {
12113
        if (quadrant == move_dir)
12114
        {
12115
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12116
            ImDrawList* draw_list = GetForegroundDrawList(window);
12117
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12118
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12119
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12120
        }
12121
    }
12122
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12123
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12124
    if (debug_hovering || debug_tty)
12125
    {
12126
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12127
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12128
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12129
        if (debug_hovering)
12130
        {
12131
            ImDrawList* draw_list = GetForegroundDrawList(window);
12132
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12133
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12134
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12135
            draw_list->AddText(cand.Max, ~0U, buf);
12136
        }
12137
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12138
    }
12139
#endif
12140
12141
    // Is it in the quadrant we're interested in moving to?
12142
0
    bool new_best = false;
12143
0
    if (quadrant == move_dir)
12144
0
    {
12145
        // Does it beat the current best candidate?
12146
0
        if (dist_box < result->DistBox)
12147
0
        {
12148
0
            result->DistBox = dist_box;
12149
0
            result->DistCenter = dist_center;
12150
0
            return true;
12151
0
        }
12152
0
        if (dist_box == result->DistBox)
12153
0
        {
12154
            // Try using distance between center points to break ties
12155
0
            if (dist_center < result->DistCenter)
12156
0
            {
12157
0
                result->DistCenter = dist_center;
12158
0
                new_best = true;
12159
0
            }
12160
0
            else if (dist_center == result->DistCenter)
12161
0
            {
12162
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12163
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12164
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12165
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12166
0
                    new_best = true;
12167
0
            }
12168
0
        }
12169
0
    }
12170
12171
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12172
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12173
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12174
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12175
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12176
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12177
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12178
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12179
0
            {
12180
0
                result->DistAxial = dist_axial;
12181
0
                new_best = true;
12182
0
            }
12183
12184
0
    return new_best;
12185
0
}
12186
12187
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12188
1
{
12189
1
    ImGuiContext& g = *GImGui;
12190
1
    ImGuiWindow* window = g.CurrentWindow;
12191
1
    result->Window = window;
12192
1
    result->ID = g.LastItemData.ID;
12193
1
    result->FocusScopeId = g.CurrentFocusScopeId;
12194
1
    result->InFlags = g.LastItemData.InFlags;
12195
1
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12196
1
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12197
0
    {
12198
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12199
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12200
0
    }
12201
1
}
12202
12203
// True when current work location may be scrolled horizontally when moving left / right.
12204
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12205
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12206
67.4k
{
12207
67.4k
    ImGuiContext& g = *GImGui;
12208
67.4k
    ImGuiWindow* window = g.CurrentWindow;
12209
67.4k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12210
67.4k
}
12211
12212
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12213
// This is called after LastItemData is set, but NextItemData is also still valid.
12214
static void ImGui::NavProcessItem()
12215
3
{
12216
3
    ImGuiContext& g = *GImGui;
12217
3
    ImGuiWindow* window = g.CurrentWindow;
12218
3
    const ImGuiID id = g.LastItemData.ID;
12219
3
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12220
12221
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12222
3
    if (window->DC.NavIsScrollPushableX == false)
12223
0
    {
12224
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12225
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12226
0
    }
12227
3
    const ImRect nav_bb = g.LastItemData.NavRect;
12228
12229
    // Process Init Request
12230
3
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12231
1
    {
12232
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12233
1
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12234
1
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12235
1
        {
12236
1
            NavApplyItemToResult(&g.NavInitResult);
12237
1
        }
12238
1
        if (candidate_for_nav_default_focus)
12239
1
        {
12240
1
            g.NavInitRequest = false; // Found a match, clear request
12241
1
            NavUpdateAnyRequestFlag();
12242
1
        }
12243
1
    }
12244
12245
    // Process Move Request (scoring for navigation)
12246
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12247
3
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12248
0
    {
12249
0
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12250
0
        {
12251
0
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12252
0
            if (is_tabbing)
12253
0
            {
12254
0
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12255
0
            }
12256
0
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12257
0
            {
12258
0
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12259
0
                if (NavScoreItem(result))
12260
0
                    NavApplyItemToResult(result);
12261
12262
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12263
0
                const float VISIBLE_RATIO = 0.70f;
12264
0
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12265
0
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12266
0
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12267
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12268
0
            }
12269
0
        }
12270
0
    }
12271
12272
    // Update information for currently focused/navigated item
12273
3
    if (g.NavId == id)
12274
0
    {
12275
0
        if (g.NavWindow != window)
12276
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12277
0
        g.NavLayer = window->DC.NavLayerCurrent;
12278
0
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12279
0
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12280
0
        g.NavIdIsAlive = true;
12281
0
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12282
0
        {
12283
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12284
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12285
0
        }
12286
0
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12287
0
    }
12288
3
}
12289
12290
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12291
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12292
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12293
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12294
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12295
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12296
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12297
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12298
0
{
12299
0
    ImGuiContext& g = *GImGui;
12300
12301
0
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12302
0
    {
12303
0
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12304
0
            return;
12305
0
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12306
0
            return;
12307
0
    }
12308
12309
    // - Can always land on an item when using API call.
12310
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12311
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12312
0
    bool can_stop;
12313
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12314
0
        can_stop = true;
12315
0
    else
12316
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12317
12318
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12319
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12320
0
    if (g.NavTabbingDir == +1)
12321
0
    {
12322
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12323
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12324
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12325
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12326
0
            NavMoveRequestResolveWithLastItem(result);
12327
0
        else if (g.NavId == id)
12328
0
            g.NavTabbingCounter = 1;
12329
0
    }
12330
0
    else if (g.NavTabbingDir == -1)
12331
0
    {
12332
        // Tab Backward
12333
0
        if (g.NavId == id)
12334
0
        {
12335
0
            if (result->ID)
12336
0
            {
12337
0
                g.NavMoveScoringItems = false;
12338
0
                NavUpdateAnyRequestFlag();
12339
0
            }
12340
0
        }
12341
0
        else if (can_stop)
12342
0
        {
12343
            // Keep applying until reaching NavId
12344
0
            NavApplyItemToResult(result);
12345
0
        }
12346
0
    }
12347
0
    else if (g.NavTabbingDir == 0)
12348
0
    {
12349
0
        if (can_stop && g.NavId == id)
12350
0
            NavMoveRequestResolveWithLastItem(result);
12351
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12352
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12353
0
    }
12354
0
}
12355
12356
bool ImGui::NavMoveRequestButNoResultYet()
12357
74
{
12358
74
    ImGuiContext& g = *GImGui;
12359
74
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12360
74
}
12361
12362
// FIXME: ScoringRect is not set
12363
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12364
0
{
12365
0
    ImGuiContext& g = *GImGui;
12366
0
    IM_ASSERT(g.NavWindow != NULL);
12367
12368
0
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12369
0
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12370
12371
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12372
0
    g.NavMoveDir = move_dir;
12373
0
    g.NavMoveDirForDebug = move_dir;
12374
0
    g.NavMoveClipDir = clip_dir;
12375
0
    g.NavMoveFlags = move_flags;
12376
0
    g.NavMoveScrollFlags = scroll_flags;
12377
0
    g.NavMoveForwardToNextFrame = false;
12378
0
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12379
0
    g.NavMoveResultLocal.Clear();
12380
0
    g.NavMoveResultLocalVisible.Clear();
12381
0
    g.NavMoveResultOther.Clear();
12382
0
    g.NavTabbingCounter = 0;
12383
0
    g.NavTabbingResultFirst.Clear();
12384
0
    NavUpdateAnyRequestFlag();
12385
0
}
12386
12387
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12388
0
{
12389
0
    ImGuiContext& g = *GImGui;
12390
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12391
0
    NavApplyItemToResult(result);
12392
0
    NavUpdateAnyRequestFlag();
12393
0
}
12394
12395
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12396
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12397
0
{
12398
0
    ImGuiContext& g = *GImGui;
12399
0
    g.NavMoveScoringItems = false;
12400
0
    g.LastItemData.ID = tree_node_data->ID;
12401
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12402
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12403
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12404
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12405
0
    NavUpdateAnyRequestFlag();
12406
0
}
12407
12408
void ImGui::NavMoveRequestCancel()
12409
22
{
12410
22
    ImGuiContext& g = *GImGui;
12411
22
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12412
22
    NavUpdateAnyRequestFlag();
12413
22
}
12414
12415
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12416
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12417
0
{
12418
0
    ImGuiContext& g = *GImGui;
12419
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12420
0
    NavMoveRequestCancel();
12421
0
    g.NavMoveForwardToNextFrame = true;
12422
0
    g.NavMoveDir = move_dir;
12423
0
    g.NavMoveClipDir = clip_dir;
12424
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12425
0
    g.NavMoveScrollFlags = scroll_flags;
12426
0
}
12427
12428
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12429
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12430
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12431
0
{
12432
0
    ImGuiContext& g = *GImGui;
12433
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12434
12435
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12436
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12437
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12438
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12439
0
}
12440
12441
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12442
// This way we could find the last focused window among our children. It would be much less confusing this way?
12443
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12444
6
{
12445
6
    ImGuiWindow* parent = nav_window;
12446
11
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12447
5
        parent = parent->ParentWindow;
12448
6
    if (parent && parent != nav_window)
12449
5
        parent->NavLastChildNavWindow = nav_window;
12450
6
}
12451
12452
// Restore the last focused child.
12453
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12454
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12455
0
{
12456
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12457
0
        return window->NavLastChildNavWindow;
12458
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12459
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12460
0
            return tab->Window;
12461
0
    return window;
12462
0
}
12463
12464
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12465
0
{
12466
0
    ImGuiContext& g = *GImGui;
12467
0
    if (layer == ImGuiNavLayer_Main)
12468
0
    {
12469
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12470
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12471
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12472
0
        if (prev_nav_window)
12473
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12474
0
    }
12475
0
    ImGuiWindow* window = g.NavWindow;
12476
0
    if (window->NavLastIds[layer] != 0)
12477
0
    {
12478
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12479
0
    }
12480
0
    else
12481
0
    {
12482
0
        g.NavLayer = layer;
12483
0
        NavInitWindow(window, true);
12484
0
    }
12485
0
}
12486
12487
void ImGui::NavRestoreHighlightAfterMove()
12488
0
{
12489
0
    ImGuiContext& g = *GImGui;
12490
0
    g.NavDisableHighlight = false;
12491
0
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12492
0
}
12493
12494
static inline void ImGui::NavUpdateAnyRequestFlag()
12495
22.4k
{
12496
22.4k
    ImGuiContext& g = *GImGui;
12497
22.4k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12498
22.4k
    if (g.NavAnyRequest)
12499
22.4k
        IM_ASSERT(g.NavWindow != NULL);
12500
22.4k
}
12501
12502
// This needs to be called before we submit any widget (aka in or before Begin)
12503
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12504
2
{
12505
    // FIXME: ChildWindow test here is wrong for docking
12506
2
    ImGuiContext& g = *GImGui;
12507
2
    IM_ASSERT(window == g.NavWindow);
12508
12509
2
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12510
0
    {
12511
0
        g.NavId = 0;
12512
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12513
0
        return;
12514
0
    }
12515
12516
2
    bool init_for_nav = false;
12517
2
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12518
2
        init_for_nav = true;
12519
2
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12520
2
    if (init_for_nav)
12521
2
    {
12522
2
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12523
2
        g.NavInitRequest = true;
12524
2
        g.NavInitRequestFromMove = false;
12525
2
        g.NavInitResult.ID = 0;
12526
2
        NavUpdateAnyRequestFlag();
12527
2
    }
12528
0
    else
12529
0
    {
12530
0
        g.NavId = window->NavLastIds[0];
12531
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12532
0
    }
12533
2
}
12534
12535
static ImVec2 ImGui::NavCalcPreferredRefPos()
12536
0
{
12537
0
    ImGuiContext& g = *GImGui;
12538
0
    ImGuiWindow* window = g.NavWindow;
12539
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12540
0
    {
12541
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12542
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12543
        // In theory we could move that +1.0f offset in OpenPopupEx()
12544
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12545
0
        return ImVec2(p.x + 1.0f, p.y);
12546
0
    }
12547
0
    else
12548
0
    {
12549
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12550
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12551
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12552
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12553
0
        {
12554
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12555
0
            rect_rel.Translate(window->Scroll - next_scroll);
12556
0
        }
12557
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12558
0
        ImGuiViewport* viewport = window->Viewport;
12559
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12560
0
    }
12561
0
}
12562
12563
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12564
0
{
12565
0
    ImGuiContext& g = *GImGui;
12566
0
    float repeat_delay, repeat_rate;
12567
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12568
12569
0
    ImGuiKey key_less, key_more;
12570
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12571
0
    {
12572
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12573
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12574
0
    }
12575
0
    else
12576
0
    {
12577
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12578
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12579
0
    }
12580
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12581
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12582
0
        amount = 0.0f;
12583
0
    return amount;
12584
0
}
12585
12586
static void ImGui::NavUpdate()
12587
22.2k
{
12588
22.2k
    ImGuiContext& g = *GImGui;
12589
22.2k
    ImGuiIO& io = g.IO;
12590
12591
22.2k
    io.WantSetMousePos = false;
12592
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12593
12594
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12595
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12596
22.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12597
22.2k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12598
22.2k
    if (nav_gamepad_active)
12599
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12600
0
            if (IsKeyDown(key))
12601
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12602
22.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12603
22.2k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12604
22.2k
    if (nav_keyboard_active)
12605
22.2k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12606
155k
            if (IsKeyDown(key))
12607
4.23k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12608
12609
    // Process navigation init request (select first/default focus)
12610
22.2k
    g.NavJustMovedToId = 0;
12611
22.2k
    if (g.NavInitResult.ID != 0)
12612
1
        NavInitRequestApplyResult();
12613
22.2k
    g.NavInitRequest = false;
12614
22.2k
    g.NavInitRequestFromMove = false;
12615
22.2k
    g.NavInitResult.ID = 0;
12616
12617
    // Process navigation move request
12618
22.2k
    if (g.NavMoveSubmitted)
12619
0
        NavMoveRequestApplyResult();
12620
22.2k
    g.NavTabbingCounter = 0;
12621
22.2k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12622
12623
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12624
22.2k
    bool set_mouse_pos = false;
12625
22.2k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12626
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12627
0
            set_mouse_pos = true;
12628
22.2k
    g.NavMousePosDirty = false;
12629
22.2k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12630
12631
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12632
22.2k
    if (g.NavWindow)
12633
6
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12634
22.2k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12635
0
        g.NavWindow->NavLastChildNavWindow = NULL;
12636
12637
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12638
22.2k
    NavUpdateWindowing();
12639
12640
    // Set output flags for user application
12641
22.2k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12642
22.2k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12643
12644
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12645
22.2k
    NavUpdateCancelRequest();
12646
12647
    // Process manual activation request
12648
22.2k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12649
22.2k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12650
22.2k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12651
0
    {
12652
0
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None));
12653
0
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None)));
12654
0
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None));
12655
0
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyPressed(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None)));
12656
0
        if (g.ActiveId == 0 && activate_pressed)
12657
0
        {
12658
0
            g.NavActivateId = g.NavId;
12659
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12660
0
        }
12661
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12662
0
        {
12663
0
            g.NavActivateId = g.NavId;
12664
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12665
0
        }
12666
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12667
0
            g.NavActivateDownId = g.NavId;
12668
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12669
0
        {
12670
0
            g.NavActivatePressedId = g.NavId;
12671
0
            NavHighlightActivated(g.NavId);
12672
0
        }
12673
0
    }
12674
22.2k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12675
0
        g.NavDisableHighlight = true;
12676
22.2k
    if (g.NavActivateId != 0)
12677
22.2k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12678
12679
    // Highlight
12680
22.2k
    if (g.NavHighlightActivatedTimer > 0.0f)
12681
0
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
12682
22.2k
    if (g.NavHighlightActivatedTimer == 0.0f)
12683
22.2k
        g.NavHighlightActivatedId = 0;
12684
12685
    // Process programmatic activation request
12686
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12687
22.2k
    if (g.NavNextActivateId != 0)
12688
0
    {
12689
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12690
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12691
0
    }
12692
22.2k
    g.NavNextActivateId = 0;
12693
12694
    // Process move requests
12695
22.2k
    NavUpdateCreateMoveRequest();
12696
22.2k
    if (g.NavMoveDir == ImGuiDir_None)
12697
22.2k
        NavUpdateCreateTabbingRequest();
12698
22.2k
    NavUpdateAnyRequestFlag();
12699
22.2k
    g.NavIdIsAlive = false;
12700
12701
    // Scrolling
12702
22.2k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12703
6
    {
12704
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12705
6
        ImGuiWindow* window = g.NavWindow;
12706
6
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12707
6
        const ImGuiDir move_dir = g.NavMoveDir;
12708
6
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12709
0
        {
12710
0
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12711
0
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12712
0
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12713
0
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12714
0
        }
12715
12716
        // *Normal* Manual scroll with LStick
12717
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12718
6
        if (nav_gamepad_active)
12719
0
        {
12720
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12721
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12722
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12723
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12724
0
            if (scroll_dir.y != 0.0f)
12725
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12726
0
        }
12727
6
    }
12728
12729
    // Always prioritize mouse highlight if navigation is disabled
12730
22.2k
    if (!nav_keyboard_active && !nav_gamepad_active)
12731
0
    {
12732
0
        g.NavDisableHighlight = true;
12733
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12734
0
    }
12735
12736
    // Update mouse position if requested
12737
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12738
22.2k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12739
0
        TeleportMousePos(NavCalcPreferredRefPos());
12740
12741
    // [DEBUG]
12742
22.2k
    g.NavScoringDebugCount = 0;
12743
#if IMGUI_DEBUG_NAV_RECTS
12744
    if (ImGuiWindow* debug_window = g.NavWindow)
12745
    {
12746
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12747
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12748
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12749
    }
12750
#endif
12751
22.2k
}
12752
12753
void ImGui::NavInitRequestApplyResult()
12754
1
{
12755
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12756
1
    ImGuiContext& g = *GImGui;
12757
1
    if (!g.NavWindow)
12758
1
        return;
12759
12760
0
    ImGuiNavItemData* result = &g.NavInitResult;
12761
0
    if (g.NavId != result->ID)
12762
0
    {
12763
0
        g.NavJustMovedToId = result->ID;
12764
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12765
0
        g.NavJustMovedToKeyMods = 0;
12766
0
    }
12767
12768
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12769
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12770
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12771
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12772
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12773
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12774
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12775
0
    if (g.NavInitRequestFromMove)
12776
0
        NavRestoreHighlightAfterMove();
12777
0
}
12778
12779
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12780
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12781
0
{
12782
    // Bias initial rect
12783
0
    ImGuiContext& g = *GImGui;
12784
0
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12785
12786
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12787
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12788
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12789
0
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12790
0
    {
12791
0
        if (preferred_pos_rel.x == FLT_MAX)
12792
0
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12793
0
        if (preferred_pos_rel.y == FLT_MAX)
12794
0
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12795
0
    }
12796
12797
    // Apply general bias on the other axis
12798
0
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12799
0
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12800
0
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12801
0
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12802
0
}
12803
12804
void ImGui::NavUpdateCreateMoveRequest()
12805
22.2k
{
12806
22.2k
    ImGuiContext& g = *GImGui;
12807
22.2k
    ImGuiIO& io = g.IO;
12808
22.2k
    ImGuiWindow* window = g.NavWindow;
12809
22.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12810
22.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12811
12812
22.2k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12813
0
    {
12814
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12815
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12816
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12817
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12818
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12819
0
    }
12820
22.2k
    else
12821
22.2k
    {
12822
        // Initiate directional inputs request
12823
22.2k
        g.NavMoveDir = ImGuiDir_None;
12824
22.2k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12825
22.2k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12826
22.2k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12827
6
        {
12828
6
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
12829
6
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12830
6
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12831
6
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12832
6
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12833
6
        }
12834
22.2k
        g.NavMoveClipDir = g.NavMoveDir;
12835
22.2k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12836
22.2k
    }
12837
12838
    // Update PageUp/PageDown/Home/End scroll
12839
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12840
22.2k
    float scoring_rect_offset_y = 0.0f;
12841
22.2k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12842
6
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12843
22.2k
    if (scoring_rect_offset_y != 0.0f)
12844
0
    {
12845
0
        g.NavScoringNoClipRect = window->InnerRect;
12846
0
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12847
0
    }
12848
12849
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12850
#if IMGUI_DEBUG_NAV_SCORING
12851
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12852
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12853
    if (io.KeyCtrl)
12854
    {
12855
        if (g.NavMoveDir == ImGuiDir_None)
12856
            g.NavMoveDir = g.NavMoveDirForDebug;
12857
        g.NavMoveClipDir = g.NavMoveDir;
12858
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12859
    }
12860
#endif
12861
12862
    // Submit
12863
22.2k
    g.NavMoveForwardToNextFrame = false;
12864
22.2k
    if (g.NavMoveDir != ImGuiDir_None)
12865
0
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12866
12867
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12868
22.2k
    if (g.NavMoveSubmitted && g.NavId == 0)
12869
0
    {
12870
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12871
0
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12872
0
        g.NavInitResult.ID = 0;
12873
0
        g.NavDisableHighlight = false;
12874
0
    }
12875
12876
    // When using gamepad, we project the reference nav bounding box into window visible area.
12877
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12878
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12879
22.2k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12880
0
    {
12881
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12882
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12883
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12884
12885
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12886
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12887
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12888
12889
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12890
0
        {
12891
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12892
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12893
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12894
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12895
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12896
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12897
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12898
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12899
0
            g.NavId = 0;
12900
0
        }
12901
0
    }
12902
12903
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12904
22.2k
    ImRect scoring_rect;
12905
22.2k
    if (window != NULL)
12906
6
    {
12907
6
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12908
6
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12909
6
        scoring_rect.TranslateY(scoring_rect_offset_y);
12910
6
        if (g.NavMoveSubmitted)
12911
0
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12912
6
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12913
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12914
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12915
6
    }
12916
22.2k
    g.NavScoringRect = scoring_rect;
12917
22.2k
    g.NavScoringNoClipRect.Add(scoring_rect);
12918
22.2k
}
12919
12920
void ImGui::NavUpdateCreateTabbingRequest()
12921
22.2k
{
12922
22.2k
    ImGuiContext& g = *GImGui;
12923
22.2k
    ImGuiWindow* window = g.NavWindow;
12924
22.2k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12925
22.2k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12926
22.2k
        return;
12927
12928
6
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12929
6
    if (!tab_pressed)
12930
6
        return;
12931
12932
    // Initiate tabbing request
12933
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12934
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12935
0
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12936
0
    if (nav_keyboard_active)
12937
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12938
0
    else
12939
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12940
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12941
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12942
0
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12943
0
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12944
0
    g.NavTabbingCounter = -1;
12945
0
}
12946
12947
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12948
void ImGui::NavMoveRequestApplyResult()
12949
0
{
12950
0
    ImGuiContext& g = *GImGui;
12951
#if IMGUI_DEBUG_NAV_SCORING
12952
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12953
        return;
12954
#endif
12955
12956
    // Select which result to use
12957
0
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12958
12959
    // Tabbing forward wrap
12960
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12961
0
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12962
0
            result = &g.NavTabbingResultFirst;
12963
12964
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12965
0
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12966
0
    if (result == NULL)
12967
0
    {
12968
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12969
0
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12970
0
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12971
0
            NavRestoreHighlightAfterMove();
12972
0
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12973
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12974
0
        return;
12975
0
    }
12976
12977
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12978
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12979
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12980
0
            result = &g.NavMoveResultLocalVisible;
12981
12982
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12983
0
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12984
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12985
0
            result = &g.NavMoveResultOther;
12986
0
    IM_ASSERT(g.NavWindow && result->Window);
12987
12988
    // Scroll to keep newly navigated item fully into view.
12989
0
    if (g.NavLayer == ImGuiNavLayer_Main)
12990
0
    {
12991
0
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12992
0
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12993
12994
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12995
0
        {
12996
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12997
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12998
0
            SetScrollY(result->Window, scroll_target);
12999
0
        }
13000
0
    }
13001
13002
0
    if (g.NavWindow != result->Window)
13003
0
    {
13004
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13005
0
        g.NavWindow = result->Window;
13006
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13007
0
    }
13008
13009
    // Clear active id unless requested not to
13010
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13011
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13012
0
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13013
0
        ClearActiveID();
13014
13015
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13016
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13017
0
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13018
0
    {
13019
0
        g.NavJustMovedToId = result->ID;
13020
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13021
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13022
0
    }
13023
13024
    // Apply new NavID/Focus
13025
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13026
0
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13027
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13028
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13029
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13030
13031
    // Restore last preferred position for current axis
13032
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13033
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13034
0
    {
13035
0
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13036
0
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13037
0
    }
13038
13039
    // Tabbing: Activates Inputable, otherwise only Focus
13040
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13041
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13042
13043
    // Activate
13044
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13045
0
    {
13046
0
        g.NavNextActivateId = result->ID;
13047
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13048
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13049
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13050
0
    }
13051
13052
    // Enable nav highlight
13053
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13054
0
        NavRestoreHighlightAfterMove();
13055
0
}
13056
13057
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13058
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13059
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13060
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13061
static void ImGui::NavUpdateCancelRequest()
13062
22.2k
{
13063
22.2k
    ImGuiContext& g = *GImGui;
13064
22.2k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13065
22.2k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13066
22.2k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
13067
21.8k
        return;
13068
13069
400
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13070
400
    if (g.ActiveId != 0)
13071
0
    {
13072
0
        ClearActiveID();
13073
0
    }
13074
400
    else if (g.NavLayer != ImGuiNavLayer_Main)
13075
0
    {
13076
        // Leave the "menu" layer
13077
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13078
0
        NavRestoreHighlightAfterMove();
13079
0
    }
13080
400
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13081
0
    {
13082
        // Exit child window
13083
0
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13084
0
        ImGuiWindow* parent_window = child_window->ParentWindow;
13085
0
        IM_ASSERT(child_window->ChildId != 0);
13086
0
        FocusWindow(parent_window);
13087
0
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13088
0
        NavRestoreHighlightAfterMove();
13089
0
    }
13090
400
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13091
0
    {
13092
        // Close open popup/menu
13093
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13094
0
    }
13095
400
    else
13096
400
    {
13097
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13098
400
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13099
0
            g.NavWindow->NavLastIds[0] = 0;
13100
400
        g.NavId = 0;
13101
400
    }
13102
400
}
13103
13104
// Handle PageUp/PageDown/Home/End keys
13105
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13106
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13107
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13108
static float ImGui::NavUpdatePageUpPageDown()
13109
6
{
13110
6
    ImGuiContext& g = *GImGui;
13111
6
    ImGuiWindow* window = g.NavWindow;
13112
6
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13113
0
        return 0.0f;
13114
13115
6
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
13116
6
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
13117
6
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13118
6
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13119
6
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13120
6
        return 0.0f;
13121
13122
0
    if (g.NavLayer != ImGuiNavLayer_Main)
13123
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13124
13125
0
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13126
0
    {
13127
        // Fallback manual-scroll when window has no navigable item
13128
0
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13129
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13130
0
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13131
0
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13132
0
        else if (home_pressed)
13133
0
            SetScrollY(window, 0.0f);
13134
0
        else if (end_pressed)
13135
0
            SetScrollY(window, window->ScrollMax.y);
13136
0
    }
13137
0
    else
13138
0
    {
13139
0
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13140
0
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13141
0
        float nav_scoring_rect_offset_y = 0.0f;
13142
0
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13143
0
        {
13144
0
            nav_scoring_rect_offset_y = -page_offset_y;
13145
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13146
0
            g.NavMoveClipDir = ImGuiDir_Up;
13147
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13148
0
        }
13149
0
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13150
0
        {
13151
0
            nav_scoring_rect_offset_y = +page_offset_y;
13152
0
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13153
0
            g.NavMoveClipDir = ImGuiDir_Down;
13154
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13155
0
        }
13156
0
        else if (home_pressed)
13157
0
        {
13158
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13159
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13160
            // Preserve current horizontal position if we have any.
13161
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13162
0
            if (nav_rect_rel.IsInverted())
13163
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13164
0
            g.NavMoveDir = ImGuiDir_Down;
13165
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13166
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13167
0
        }
13168
0
        else if (end_pressed)
13169
0
        {
13170
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13171
0
            if (nav_rect_rel.IsInverted())
13172
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13173
0
            g.NavMoveDir = ImGuiDir_Up;
13174
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13175
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13176
0
        }
13177
0
        return nav_scoring_rect_offset_y;
13178
0
    }
13179
0
    return 0.0f;
13180
0
}
13181
13182
static void ImGui::NavEndFrame()
13183
22.2k
{
13184
22.2k
    ImGuiContext& g = *GImGui;
13185
13186
    // Show CTRL+TAB list window
13187
22.2k
    if (g.NavWindowingTarget != NULL)
13188
0
        NavUpdateWindowingOverlay();
13189
13190
    // Perform wrap-around in menus
13191
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13192
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13193
22.2k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13194
0
        NavUpdateCreateWrappingRequest();
13195
22.2k
}
13196
13197
static void ImGui::NavUpdateCreateWrappingRequest()
13198
0
{
13199
0
    ImGuiContext& g = *GImGui;
13200
0
    ImGuiWindow* window = g.NavWindow;
13201
13202
0
    bool do_forward = false;
13203
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13204
0
    ImGuiDir clip_dir = g.NavMoveDir;
13205
13206
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13207
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13208
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13209
0
    {
13210
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13211
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13212
0
        {
13213
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13214
0
            clip_dir = ImGuiDir_Up;
13215
0
        }
13216
0
        do_forward = true;
13217
0
    }
13218
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13219
0
    {
13220
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13221
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13222
0
        {
13223
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13224
0
            clip_dir = ImGuiDir_Down;
13225
0
        }
13226
0
        do_forward = true;
13227
0
    }
13228
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13229
0
    {
13230
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13231
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13232
0
        {
13233
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13234
0
            clip_dir = ImGuiDir_Left;
13235
0
        }
13236
0
        do_forward = true;
13237
0
    }
13238
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13239
0
    {
13240
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13241
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13242
0
        {
13243
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13244
0
            clip_dir = ImGuiDir_Right;
13245
0
        }
13246
0
        do_forward = true;
13247
0
    }
13248
0
    if (!do_forward)
13249
0
        return;
13250
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13251
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13252
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13253
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13254
0
}
13255
13256
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13257
0
{
13258
0
    ImGuiContext& g = *GImGui;
13259
0
    IM_UNUSED(g);
13260
0
    int order = window->FocusOrder;
13261
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13262
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13263
0
    return order;
13264
0
}
13265
13266
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13267
0
{
13268
0
    ImGuiContext& g = *GImGui;
13269
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13270
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13271
0
            return g.WindowsFocusOrder[i];
13272
0
    return NULL;
13273
0
}
13274
13275
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13276
0
{
13277
0
    ImGuiContext& g = *GImGui;
13278
0
    IM_ASSERT(g.NavWindowingTarget);
13279
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13280
0
        return;
13281
13282
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13283
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13284
0
    if (!window_target)
13285
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13286
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13287
0
    {
13288
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13289
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13290
0
    }
13291
0
    g.NavWindowingToggleLayer = false;
13292
0
}
13293
13294
// Windowing management mode
13295
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13296
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13297
static void ImGui::NavUpdateWindowing()
13298
22.2k
{
13299
22.2k
    ImGuiContext& g = *GImGui;
13300
22.2k
    ImGuiIO& io = g.IO;
13301
13302
22.2k
    ImGuiWindow* apply_focus_window = NULL;
13303
22.2k
    bool apply_toggle_layer = false;
13304
13305
22.2k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13306
22.2k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13307
22.2k
    if (!allow_windowing)
13308
0
        g.NavWindowingTarget = NULL;
13309
13310
    // Fade out
13311
22.2k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13312
0
    {
13313
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13314
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13315
0
            g.NavWindowingTargetAnim = NULL;
13316
0
    }
13317
13318
    // Start CTRL+Tab or Square+L/R window selection
13319
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13320
22.2k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13321
22.2k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13322
22.2k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13323
22.2k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13324
22.2k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13325
22.2k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
13326
22.2k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13327
22.2k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13328
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13329
0
        {
13330
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13331
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13332
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13333
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13334
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13335
13336
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13337
0
            if (keyboard_next_window || keyboard_prev_window)
13338
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13339
0
        }
13340
13341
    // Gamepad update
13342
22.2k
    g.NavWindowingTimer += io.DeltaTime;
13343
22.2k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13344
0
    {
13345
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13346
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13347
13348
        // Select window to focus
13349
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13350
0
        if (focus_change_dir != 0)
13351
0
        {
13352
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13353
0
            g.NavWindowingHighlightAlpha = 1.0f;
13354
0
        }
13355
13356
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13357
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13358
0
        {
13359
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13360
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13361
0
                apply_toggle_layer = true;
13362
0
            else if (!g.NavWindowingToggleLayer)
13363
0
                apply_focus_window = g.NavWindowingTarget;
13364
0
            g.NavWindowingTarget = NULL;
13365
0
        }
13366
0
    }
13367
13368
    // Keyboard: Focus
13369
22.2k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13370
0
    {
13371
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13372
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13373
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13374
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13375
0
        if (keyboard_next_window || keyboard_prev_window)
13376
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13377
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13378
0
            apply_focus_window = g.NavWindowingTarget;
13379
0
    }
13380
13381
    // Keyboard: Press and Release ALT to toggle menu layer
13382
22.2k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13383
22.2k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13384
44.3k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, ImGuiKeyOwner_None))
13385
650
        {
13386
650
            g.NavWindowingToggleLayer = true;
13387
650
            g.NavWindowingToggleKey = windowing_toggle_key;
13388
650
            g.NavInputSource = ImGuiInputSource_Keyboard;
13389
650
            break;
13390
650
        }
13391
22.2k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13392
1.79k
    {
13393
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13394
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13395
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13396
        // We cancel toggling nav layer if an owner has claimed the key.
13397
1.79k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13398
58
            g.NavWindowingToggleLayer = false;
13399
1.79k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_None) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13400
0
            g.NavWindowingToggleLayer = false;
13401
13402
        // Apply layer toggle on Alt release
13403
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13404
1.79k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13405
358
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13406
358
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13407
357
                    apply_toggle_layer = true;
13408
1.79k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13409
579
            g.NavWindowingToggleLayer = false;
13410
1.79k
    }
13411
13412
    // Move window
13413
22.2k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13414
0
    {
13415
0
        ImVec2 nav_move_dir;
13416
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13417
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13418
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13419
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13420
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13421
0
        {
13422
0
            const float NAV_MOVE_SPEED = 800.0f;
13423
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13424
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13425
0
            g.NavDisableMouseHover = true;
13426
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13427
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13428
0
            {
13429
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13430
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13431
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13432
0
            }
13433
0
        }
13434
0
    }
13435
13436
    // Apply final focus
13437
22.2k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13438
0
    {
13439
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13440
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13441
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13442
0
        ClearActiveID();
13443
0
        NavRestoreHighlightAfterMove();
13444
0
        ClosePopupsOverWindow(apply_focus_window, false);
13445
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13446
0
        apply_focus_window = g.NavWindow;
13447
0
        if (apply_focus_window->NavLastIds[0] == 0)
13448
0
            NavInitWindow(apply_focus_window, false);
13449
13450
        // If the window has ONLY a menu layer (no main layer), select it directly
13451
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13452
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13453
        // the target window as already been previewed once.
13454
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13455
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13456
        // won't be valid.
13457
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13458
0
            g.NavLayer = ImGuiNavLayer_Menu;
13459
13460
        // Request OS level focus
13461
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13462
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13463
0
    }
13464
22.2k
    if (apply_focus_window)
13465
0
        g.NavWindowingTarget = NULL;
13466
13467
    // Apply menu/layer toggle
13468
22.2k
    if (apply_toggle_layer && g.NavWindow)
13469
0
    {
13470
0
        ClearActiveID();
13471
13472
        // Move to parent menu if necessary
13473
0
        ImGuiWindow* new_nav_window = g.NavWindow;
13474
0
        while (new_nav_window->ParentWindow
13475
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13476
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13477
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13478
0
            new_nav_window = new_nav_window->ParentWindow;
13479
0
        if (new_nav_window != g.NavWindow)
13480
0
        {
13481
0
            ImGuiWindow* old_nav_window = g.NavWindow;
13482
0
            FocusWindow(new_nav_window);
13483
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13484
0
        }
13485
13486
        // Toggle layer
13487
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13488
0
        if (new_nav_layer != g.NavLayer)
13489
0
        {
13490
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13491
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13492
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13493
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13494
0
            NavRestoreLayer(new_nav_layer);
13495
0
            NavRestoreHighlightAfterMove();
13496
0
        }
13497
0
    }
13498
22.2k
}
13499
13500
// Window has already passed the IsWindowNavFocusable()
13501
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13502
0
{
13503
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13504
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13505
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13506
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13507
0
    if (window->DockNodeAsHost)
13508
0
        return "(Dock node)"; // Not normally shown to user.
13509
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13510
0
}
13511
13512
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13513
void ImGui::NavUpdateWindowingOverlay()
13514
0
{
13515
0
    ImGuiContext& g = *GImGui;
13516
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13517
13518
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13519
0
        return;
13520
13521
0
    if (g.NavWindowingListWindow == NULL)
13522
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13523
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13524
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13525
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13526
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13527
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13528
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13529
0
    {
13530
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13531
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13532
0
        if (!IsWindowNavFocusable(window))
13533
0
            continue;
13534
0
        const char* label = window->Name;
13535
0
        if (label == FindRenderedTextEnd(label))
13536
0
            label = GetFallbackWindowNameForWindowingList(window);
13537
0
        Selectable(label, g.NavWindowingTarget == window);
13538
0
    }
13539
0
    End();
13540
0
    PopStyleVar();
13541
0
}
13542
13543
13544
//-----------------------------------------------------------------------------
13545
// [SECTION] DRAG AND DROP
13546
//-----------------------------------------------------------------------------
13547
13548
bool ImGui::IsDragDropActive()
13549
0
{
13550
0
    ImGuiContext& g = *GImGui;
13551
0
    return g.DragDropActive;
13552
0
}
13553
13554
void ImGui::ClearDragDrop()
13555
0
{
13556
0
    ImGuiContext& g = *GImGui;
13557
0
    g.DragDropActive = false;
13558
0
    g.DragDropPayload.Clear();
13559
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13560
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13561
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13562
0
    g.DragDropAcceptFrameCount = -1;
13563
13564
0
    g.DragDropPayloadBufHeap.clear();
13565
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13566
0
}
13567
13568
bool ImGui::BeginTooltipHidden()
13569
0
{
13570
0
    ImGuiContext& g = *GImGui;
13571
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13572
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13573
0
    return ret;
13574
0
}
13575
13576
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13577
// If the item has an identifier:
13578
// - This assume/require the item to be activated (typically via ButtonBehavior).
13579
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13580
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13581
// If the item has no identifier:
13582
// - Currently always assume left mouse button.
13583
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13584
6
{
13585
6
    ImGuiContext& g = *GImGui;
13586
6
    ImGuiWindow* window = g.CurrentWindow;
13587
13588
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13589
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13590
6
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13591
13592
6
    bool source_drag_active = false;
13593
6
    ImGuiID source_id = 0;
13594
6
    ImGuiID source_parent_id = 0;
13595
6
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13596
6
    {
13597
6
        source_id = g.LastItemData.ID;
13598
6
        if (source_id != 0)
13599
6
        {
13600
            // Common path: items with ID
13601
6
            if (g.ActiveId != source_id)
13602
0
                return false;
13603
6
            if (g.ActiveIdMouseButton != -1)
13604
0
                mouse_button = g.ActiveIdMouseButton;
13605
6
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13606
0
                return false;
13607
6
            g.ActiveIdAllowOverlap = false;
13608
6
        }
13609
0
        else
13610
0
        {
13611
            // Uncommon path: items without ID
13612
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13613
0
                return false;
13614
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13615
0
                return false;
13616
13617
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13618
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13619
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13620
0
            {
13621
0
                IM_ASSERT(0);
13622
0
                return false;
13623
0
            }
13624
13625
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13626
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13627
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13628
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13629
            // Rely on keeping other window->LastItemXXX fields intact.
13630
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13631
0
            KeepAliveID(source_id);
13632
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13633
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13634
0
            {
13635
0
                SetActiveID(source_id, window);
13636
0
                FocusWindow(window);
13637
0
            }
13638
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13639
0
                g.ActiveIdAllowOverlap = is_hovered;
13640
0
        }
13641
6
        if (g.ActiveId != source_id)
13642
0
            return false;
13643
6
        source_parent_id = window->IDStack.back();
13644
6
        source_drag_active = IsMouseDragging(mouse_button);
13645
13646
        // Disable navigation and key inputs while dragging + cancel existing request if any
13647
6
        SetActiveIdUsingAllKeyboardKeys();
13648
6
    }
13649
0
    else
13650
0
    {
13651
0
        window = NULL;
13652
0
        source_id = ImHashStr("#SourceExtern");
13653
0
        source_drag_active = true;
13654
0
    }
13655
13656
6
    if (source_drag_active)
13657
0
    {
13658
0
        if (!g.DragDropActive)
13659
0
        {
13660
0
            IM_ASSERT(source_id != 0);
13661
0
            ClearDragDrop();
13662
0
            ImGuiPayload& payload = g.DragDropPayload;
13663
0
            payload.SourceId = source_id;
13664
0
            payload.SourceParentId = source_parent_id;
13665
0
            g.DragDropActive = true;
13666
0
            g.DragDropSourceFlags = flags;
13667
0
            g.DragDropMouseButton = mouse_button;
13668
0
            if (payload.SourceId == g.ActiveId)
13669
0
                g.ActiveIdNoClearOnFocusLoss = true;
13670
0
        }
13671
0
        g.DragDropSourceFrameCount = g.FrameCount;
13672
0
        g.DragDropWithinSource = true;
13673
13674
0
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13675
0
        {
13676
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13677
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13678
0
            bool ret;
13679
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13680
0
                ret = BeginTooltipHidden();
13681
0
            else
13682
0
                ret = BeginTooltip();
13683
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13684
0
            IM_UNUSED(ret);
13685
0
        }
13686
13687
0
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13688
0
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13689
13690
0
        return true;
13691
0
    }
13692
6
    return false;
13693
6
}
13694
13695
void ImGui::EndDragDropSource()
13696
0
{
13697
0
    ImGuiContext& g = *GImGui;
13698
0
    IM_ASSERT(g.DragDropActive);
13699
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13700
13701
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13702
0
        EndTooltip();
13703
13704
    // Discard the drag if have not called SetDragDropPayload()
13705
0
    if (g.DragDropPayload.DataFrameCount == -1)
13706
0
        ClearDragDrop();
13707
0
    g.DragDropWithinSource = false;
13708
0
}
13709
13710
// Use 'cond' to choose to submit payload on drag start or every frame
13711
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13712
0
{
13713
0
    ImGuiContext& g = *GImGui;
13714
0
    ImGuiPayload& payload = g.DragDropPayload;
13715
0
    if (cond == 0)
13716
0
        cond = ImGuiCond_Always;
13717
13718
0
    IM_ASSERT(type != NULL);
13719
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13720
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13721
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13722
0
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13723
13724
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13725
0
    {
13726
        // Copy payload
13727
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13728
0
        g.DragDropPayloadBufHeap.resize(0);
13729
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13730
0
        {
13731
            // Store in heap
13732
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13733
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13734
0
            memcpy(payload.Data, data, data_size);
13735
0
        }
13736
0
        else if (data_size > 0)
13737
0
        {
13738
            // Store locally
13739
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13740
0
            payload.Data = g.DragDropPayloadBufLocal;
13741
0
            memcpy(payload.Data, data, data_size);
13742
0
        }
13743
0
        else
13744
0
        {
13745
0
            payload.Data = NULL;
13746
0
        }
13747
0
        payload.DataSize = (int)data_size;
13748
0
    }
13749
0
    payload.DataFrameCount = g.FrameCount;
13750
13751
    // Return whether the payload has been accepted
13752
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13753
0
}
13754
13755
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13756
0
{
13757
0
    ImGuiContext& g = *GImGui;
13758
0
    if (!g.DragDropActive)
13759
0
        return false;
13760
13761
0
    ImGuiWindow* window = g.CurrentWindow;
13762
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13763
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13764
0
        return false;
13765
0
    IM_ASSERT(id != 0);
13766
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13767
0
        return false;
13768
0
    if (window->SkipItems)
13769
0
        return false;
13770
13771
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13772
0
    g.DragDropTargetRect = bb;
13773
0
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
13774
0
    g.DragDropTargetId = id;
13775
0
    g.DragDropWithinTarget = true;
13776
0
    return true;
13777
0
}
13778
13779
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13780
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13781
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13782
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13783
bool ImGui::BeginDragDropTarget()
13784
0
{
13785
0
    ImGuiContext& g = *GImGui;
13786
0
    if (!g.DragDropActive)
13787
0
        return false;
13788
13789
0
    ImGuiWindow* window = g.CurrentWindow;
13790
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13791
0
        return false;
13792
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13793
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13794
0
        return false;
13795
13796
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13797
0
    ImGuiID id = g.LastItemData.ID;
13798
0
    if (id == 0)
13799
0
    {
13800
0
        id = window->GetIDFromRectangle(display_rect);
13801
0
        KeepAliveID(id);
13802
0
    }
13803
0
    if (g.DragDropPayload.SourceId == id)
13804
0
        return false;
13805
13806
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13807
0
    g.DragDropTargetRect = display_rect;
13808
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13809
0
    g.DragDropTargetId = id;
13810
0
    g.DragDropWithinTarget = true;
13811
0
    return true;
13812
0
}
13813
13814
bool ImGui::IsDragDropPayloadBeingAccepted()
13815
16
{
13816
16
    ImGuiContext& g = *GImGui;
13817
16
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13818
16
}
13819
13820
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13821
0
{
13822
0
    ImGuiContext& g = *GImGui;
13823
0
    ImGuiPayload& payload = g.DragDropPayload;
13824
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13825
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13826
0
    if (type != NULL && !payload.IsDataType(type))
13827
0
        return NULL;
13828
13829
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13830
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13831
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13832
0
    ImRect r = g.DragDropTargetRect;
13833
0
    float r_surface = r.GetWidth() * r.GetHeight();
13834
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13835
0
        return NULL;
13836
13837
0
    g.DragDropAcceptFlags = flags;
13838
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13839
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13840
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13841
13842
    // Render default drop visuals
13843
0
    payload.Preview = was_accepted_previously;
13844
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13845
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13846
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
13847
13848
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13849
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13850
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13851
0
        return NULL;
13852
13853
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13854
0
    return &payload;
13855
0
}
13856
13857
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13858
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13859
0
{
13860
0
    ImGuiContext& g = *GImGui;
13861
0
    ImGuiWindow* window = g.CurrentWindow;
13862
0
    ImRect bb_display = bb;
13863
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13864
0
    bb_display.Expand(3.5f);
13865
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13866
0
    if (push_clip_rect)
13867
0
        window->DrawList->PushClipRectFullScreen();
13868
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13869
0
    if (push_clip_rect)
13870
0
        window->DrawList->PopClipRect();
13871
0
}
13872
13873
const ImGuiPayload* ImGui::GetDragDropPayload()
13874
0
{
13875
0
    ImGuiContext& g = *GImGui;
13876
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13877
0
}
13878
13879
void ImGui::EndDragDropTarget()
13880
0
{
13881
0
    ImGuiContext& g = *GImGui;
13882
0
    IM_ASSERT(g.DragDropActive);
13883
0
    IM_ASSERT(g.DragDropWithinTarget);
13884
0
    g.DragDropWithinTarget = false;
13885
13886
    // Clear drag and drop state payload right after delivery
13887
0
    if (g.DragDropPayload.Delivery)
13888
0
        ClearDragDrop();
13889
0
}
13890
13891
//-----------------------------------------------------------------------------
13892
// [SECTION] LOGGING/CAPTURING
13893
//-----------------------------------------------------------------------------
13894
// All text output from the interface can be captured into tty/file/clipboard.
13895
// By default, tree nodes are automatically opened during logging.
13896
//-----------------------------------------------------------------------------
13897
13898
// Pass text data straight to log (without being displayed)
13899
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13900
0
{
13901
0
    if (g.LogFile)
13902
0
    {
13903
0
        g.LogBuffer.Buf.resize(0);
13904
0
        g.LogBuffer.appendfv(fmt, args);
13905
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13906
0
    }
13907
0
    else
13908
0
    {
13909
0
        g.LogBuffer.appendfv(fmt, args);
13910
0
    }
13911
0
}
13912
13913
void ImGui::LogText(const char* fmt, ...)
13914
0
{
13915
0
    ImGuiContext& g = *GImGui;
13916
0
    if (!g.LogEnabled)
13917
0
        return;
13918
13919
0
    va_list args;
13920
0
    va_start(args, fmt);
13921
0
    LogTextV(g, fmt, args);
13922
0
    va_end(args);
13923
0
}
13924
13925
void ImGui::LogTextV(const char* fmt, va_list args)
13926
0
{
13927
0
    ImGuiContext& g = *GImGui;
13928
0
    if (!g.LogEnabled)
13929
0
        return;
13930
13931
0
    LogTextV(g, fmt, args);
13932
0
}
13933
13934
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13935
// We split text into individual lines to add current tree level padding
13936
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13937
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13938
0
{
13939
0
    ImGuiContext& g = *GImGui;
13940
0
    ImGuiWindow* window = g.CurrentWindow;
13941
13942
0
    const char* prefix = g.LogNextPrefix;
13943
0
    const char* suffix = g.LogNextSuffix;
13944
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13945
13946
0
    if (!text_end)
13947
0
        text_end = FindRenderedTextEnd(text, text_end);
13948
13949
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13950
0
    if (ref_pos)
13951
0
        g.LogLinePosY = ref_pos->y;
13952
0
    if (log_new_line)
13953
0
    {
13954
0
        LogText(IM_NEWLINE);
13955
0
        g.LogLineFirstItem = true;
13956
0
    }
13957
13958
0
    if (prefix)
13959
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13960
13961
    // Re-adjust padding if we have popped out of our starting depth
13962
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13963
0
        g.LogDepthRef = window->DC.TreeDepth;
13964
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13965
13966
0
    const char* text_remaining = text;
13967
0
    for (;;)
13968
0
    {
13969
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13970
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13971
0
        const char* line_start = text_remaining;
13972
0
        const char* line_end = ImStreolRange(line_start, text_end);
13973
0
        const bool is_last_line = (line_end == text_end);
13974
0
        if (line_start != line_end || !is_last_line)
13975
0
        {
13976
0
            const int line_length = (int)(line_end - line_start);
13977
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13978
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13979
0
            g.LogLineFirstItem = false;
13980
0
            if (*line_end == '\n')
13981
0
            {
13982
0
                LogText(IM_NEWLINE);
13983
0
                g.LogLineFirstItem = true;
13984
0
            }
13985
0
        }
13986
0
        if (is_last_line)
13987
0
            break;
13988
0
        text_remaining = line_end + 1;
13989
0
    }
13990
13991
0
    if (suffix)
13992
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13993
0
}
13994
13995
// Start logging/capturing text output
13996
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13997
0
{
13998
0
    ImGuiContext& g = *GImGui;
13999
0
    ImGuiWindow* window = g.CurrentWindow;
14000
0
    IM_ASSERT(g.LogEnabled == false);
14001
0
    IM_ASSERT(g.LogFile == NULL);
14002
0
    IM_ASSERT(g.LogBuffer.empty());
14003
0
    g.LogEnabled = true;
14004
0
    g.LogType = type;
14005
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14006
0
    g.LogDepthRef = window->DC.TreeDepth;
14007
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14008
0
    g.LogLinePosY = FLT_MAX;
14009
0
    g.LogLineFirstItem = true;
14010
0
}
14011
14012
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14013
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14014
0
{
14015
0
    ImGuiContext& g = *GImGui;
14016
0
    g.LogNextPrefix = prefix;
14017
0
    g.LogNextSuffix = suffix;
14018
0
}
14019
14020
void ImGui::LogToTTY(int auto_open_depth)
14021
0
{
14022
0
    ImGuiContext& g = *GImGui;
14023
0
    if (g.LogEnabled)
14024
0
        return;
14025
0
    IM_UNUSED(auto_open_depth);
14026
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14027
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14028
0
    g.LogFile = stdout;
14029
0
#endif
14030
0
}
14031
14032
// Start logging/capturing text output to given file
14033
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14034
0
{
14035
0
    ImGuiContext& g = *GImGui;
14036
0
    if (g.LogEnabled)
14037
0
        return;
14038
14039
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14040
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14041
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14042
0
    if (!filename)
14043
0
        filename = g.IO.LogFilename;
14044
0
    if (!filename || !filename[0])
14045
0
        return;
14046
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14047
0
    if (!f)
14048
0
    {
14049
0
        IM_ASSERT(0);
14050
0
        return;
14051
0
    }
14052
14053
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14054
0
    g.LogFile = f;
14055
0
}
14056
14057
// Start logging/capturing text output to clipboard
14058
void ImGui::LogToClipboard(int auto_open_depth)
14059
0
{
14060
0
    ImGuiContext& g = *GImGui;
14061
0
    if (g.LogEnabled)
14062
0
        return;
14063
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14064
0
}
14065
14066
void ImGui::LogToBuffer(int auto_open_depth)
14067
0
{
14068
0
    ImGuiContext& g = *GImGui;
14069
0
    if (g.LogEnabled)
14070
0
        return;
14071
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14072
0
}
14073
14074
void ImGui::LogFinish()
14075
44.4k
{
14076
44.4k
    ImGuiContext& g = *GImGui;
14077
44.4k
    if (!g.LogEnabled)
14078
44.4k
        return;
14079
14080
0
    LogText(IM_NEWLINE);
14081
0
    switch (g.LogType)
14082
0
    {
14083
0
    case ImGuiLogType_TTY:
14084
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14085
0
        fflush(g.LogFile);
14086
0
#endif
14087
0
        break;
14088
0
    case ImGuiLogType_File:
14089
0
        ImFileClose(g.LogFile);
14090
0
        break;
14091
0
    case ImGuiLogType_Buffer:
14092
0
        break;
14093
0
    case ImGuiLogType_Clipboard:
14094
0
        if (!g.LogBuffer.empty())
14095
0
            SetClipboardText(g.LogBuffer.begin());
14096
0
        break;
14097
0
    case ImGuiLogType_None:
14098
0
        IM_ASSERT(0);
14099
0
        break;
14100
0
    }
14101
14102
0
    g.LogEnabled = false;
14103
0
    g.LogType = ImGuiLogType_None;
14104
0
    g.LogFile = NULL;
14105
0
    g.LogBuffer.clear();
14106
0
}
14107
14108
// Helper to display logging buttons
14109
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14110
void ImGui::LogButtons()
14111
0
{
14112
0
    ImGuiContext& g = *GImGui;
14113
14114
0
    PushID("LogButtons");
14115
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14116
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14117
#else
14118
    const bool log_to_tty = false;
14119
#endif
14120
0
    const bool log_to_file = Button("Log To File"); SameLine();
14121
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14122
0
    PushTabStop(false);
14123
0
    SetNextItemWidth(80.0f);
14124
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14125
0
    PopTabStop();
14126
0
    PopID();
14127
14128
    // Start logging at the end of the function so that the buttons don't appear in the log
14129
0
    if (log_to_tty)
14130
0
        LogToTTY();
14131
0
    if (log_to_file)
14132
0
        LogToFile();
14133
0
    if (log_to_clipboard)
14134
0
        LogToClipboard();
14135
0
}
14136
14137
14138
//-----------------------------------------------------------------------------
14139
// [SECTION] SETTINGS
14140
//-----------------------------------------------------------------------------
14141
// - UpdateSettings() [Internal]
14142
// - MarkIniSettingsDirty() [Internal]
14143
// - FindSettingsHandler() [Internal]
14144
// - ClearIniSettings() [Internal]
14145
// - LoadIniSettingsFromDisk()
14146
// - LoadIniSettingsFromMemory()
14147
// - SaveIniSettingsToDisk()
14148
// - SaveIniSettingsToMemory()
14149
//-----------------------------------------------------------------------------
14150
// - CreateNewWindowSettings() [Internal]
14151
// - FindWindowSettingsByID() [Internal]
14152
// - FindWindowSettingsByWindow() [Internal]
14153
// - ClearWindowSettings() [Internal]
14154
// - WindowSettingsHandler_***() [Internal]
14155
//-----------------------------------------------------------------------------
14156
14157
// Called by NewFrame()
14158
void ImGui::UpdateSettings()
14159
22.2k
{
14160
    // Load settings on first frame (if not explicitly loaded manually before)
14161
22.2k
    ImGuiContext& g = *GImGui;
14162
22.2k
    if (!g.SettingsLoaded)
14163
1
    {
14164
1
        IM_ASSERT(g.SettingsWindows.empty());
14165
1
        if (g.IO.IniFilename)
14166
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14167
1
        g.SettingsLoaded = true;
14168
1
    }
14169
14170
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14171
22.2k
    if (g.SettingsDirtyTimer > 0.0f)
14172
900
    {
14173
900
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14174
900
        if (g.SettingsDirtyTimer <= 0.0f)
14175
3
        {
14176
3
            if (g.IO.IniFilename != NULL)
14177
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14178
3
            else
14179
3
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14180
3
            g.SettingsDirtyTimer = 0.0f;
14181
3
        }
14182
900
    }
14183
22.2k
}
14184
14185
void ImGui::MarkIniSettingsDirty()
14186
0
{
14187
0
    ImGuiContext& g = *GImGui;
14188
0
    if (g.SettingsDirtyTimer <= 0.0f)
14189
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14190
0
}
14191
14192
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14193
441
{
14194
441
    ImGuiContext& g = *GImGui;
14195
441
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14196
9
        if (g.SettingsDirtyTimer <= 0.0f)
14197
3
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14198
441
}
14199
14200
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14201
2
{
14202
2
    ImGuiContext& g = *GImGui;
14203
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14204
2
    g.SettingsHandlers.push_back(*handler);
14205
2
}
14206
14207
void ImGui::RemoveSettingsHandler(const char* type_name)
14208
0
{
14209
0
    ImGuiContext& g = *GImGui;
14210
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14211
0
        g.SettingsHandlers.erase(handler);
14212
0
}
14213
14214
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14215
2
{
14216
2
    ImGuiContext& g = *GImGui;
14217
2
    const ImGuiID type_hash = ImHashStr(type_name);
14218
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14219
1
        if (handler.TypeHash == type_hash)
14220
0
            return &handler;
14221
2
    return NULL;
14222
2
}
14223
14224
// Clear all settings (windows, tables, docking etc.)
14225
void ImGui::ClearIniSettings()
14226
0
{
14227
0
    ImGuiContext& g = *GImGui;
14228
0
    g.SettingsIniData.clear();
14229
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14230
0
        if (handler.ClearAllFn != NULL)
14231
0
            handler.ClearAllFn(&g, &handler);
14232
0
}
14233
14234
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14235
0
{
14236
0
    size_t file_data_size = 0;
14237
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14238
0
    if (!file_data)
14239
0
        return;
14240
0
    if (file_data_size > 0)
14241
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14242
0
    IM_FREE(file_data);
14243
0
}
14244
14245
// Zero-tolerance, no error reporting, cheap .ini parsing
14246
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14247
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14248
0
{
14249
0
    ImGuiContext& g = *GImGui;
14250
0
    IM_ASSERT(g.Initialized);
14251
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14252
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14253
14254
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14255
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14256
0
    if (ini_size == 0)
14257
0
        ini_size = strlen(ini_data);
14258
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14259
0
    char* const buf = g.SettingsIniData.Buf.Data;
14260
0
    char* const buf_end = buf + ini_size;
14261
0
    memcpy(buf, ini_data, ini_size);
14262
0
    buf_end[0] = 0;
14263
14264
    // Call pre-read handlers
14265
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14266
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14267
0
        if (handler.ReadInitFn != NULL)
14268
0
            handler.ReadInitFn(&g, &handler);
14269
14270
0
    void* entry_data = NULL;
14271
0
    ImGuiSettingsHandler* entry_handler = NULL;
14272
14273
0
    char* line_end = NULL;
14274
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14275
0
    {
14276
        // Skip new lines markers, then find end of the line
14277
0
        while (*line == '\n' || *line == '\r')
14278
0
            line++;
14279
0
        line_end = line;
14280
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14281
0
            line_end++;
14282
0
        line_end[0] = 0;
14283
0
        if (line[0] == ';')
14284
0
            continue;
14285
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14286
0
        {
14287
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14288
0
            line_end[-1] = 0;
14289
0
            const char* name_end = line_end - 1;
14290
0
            const char* type_start = line + 1;
14291
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14292
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14293
0
            if (!type_end || !name_start)
14294
0
                continue;
14295
0
            *type_end = 0; // Overwrite first ']'
14296
0
            name_start++;  // Skip second '['
14297
0
            entry_handler = FindSettingsHandler(type_start);
14298
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14299
0
        }
14300
0
        else if (entry_handler != NULL && entry_data != NULL)
14301
0
        {
14302
            // Let type handler parse the line
14303
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14304
0
        }
14305
0
    }
14306
0
    g.SettingsLoaded = true;
14307
14308
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14309
0
    memcpy(buf, ini_data, ini_size);
14310
14311
    // Call post-read handlers
14312
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14313
0
        if (handler.ApplyAllFn != NULL)
14314
0
            handler.ApplyAllFn(&g, &handler);
14315
0
}
14316
14317
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14318
0
{
14319
0
    ImGuiContext& g = *GImGui;
14320
0
    g.SettingsDirtyTimer = 0.0f;
14321
0
    if (!ini_filename)
14322
0
        return;
14323
14324
0
    size_t ini_data_size = 0;
14325
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14326
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14327
0
    if (!f)
14328
0
        return;
14329
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14330
0
    ImFileClose(f);
14331
0
}
14332
14333
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14334
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14335
0
{
14336
0
    ImGuiContext& g = *GImGui;
14337
0
    g.SettingsDirtyTimer = 0.0f;
14338
0
    g.SettingsIniData.Buf.resize(0);
14339
0
    g.SettingsIniData.Buf.push_back(0);
14340
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14341
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14342
0
    if (out_size)
14343
0
        *out_size = (size_t)g.SettingsIniData.size();
14344
0
    return g.SettingsIniData.c_str();
14345
0
}
14346
14347
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14348
0
{
14349
0
    ImGuiContext& g = *GImGui;
14350
14351
0
    if (g.IO.ConfigDebugIniSettings == false)
14352
0
    {
14353
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14354
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14355
0
        if (const char* p = strstr(name, "###"))
14356
0
            name = p;
14357
0
    }
14358
0
    const size_t name_len = strlen(name);
14359
14360
    // Allocate chunk
14361
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14362
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14363
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14364
0
    settings->ID = ImHashStr(name, name_len);
14365
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14366
14367
0
    return settings;
14368
0
}
14369
14370
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14371
// This is called once per window .ini entry + once per newly instantiated window.
14372
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14373
2
{
14374
2
    ImGuiContext& g = *GImGui;
14375
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14376
0
        if (settings->ID == id && !settings->WantDelete)
14377
0
            return settings;
14378
2
    return NULL;
14379
2
}
14380
14381
// This is faster if you are holding on a Window already as we don't need to perform a search.
14382
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14383
2
{
14384
2
    ImGuiContext& g = *GImGui;
14385
2
    if (window->SettingsOffset != -1)
14386
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14387
2
    return FindWindowSettingsByID(window->ID);
14388
2
}
14389
14390
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14391
void ImGui::ClearWindowSettings(const char* name)
14392
0
{
14393
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14394
0
    ImGuiContext& g = *GImGui;
14395
0
    ImGuiWindow* window = FindWindowByName(name);
14396
0
    if (window != NULL)
14397
0
    {
14398
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14399
0
        InitOrLoadWindowSettings(window, NULL);
14400
0
        if (window->DockId != 0)
14401
0
            DockContextProcessUndockWindow(&g, window, true);
14402
0
    }
14403
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14404
0
        settings->WantDelete = true;
14405
0
}
14406
14407
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14408
0
{
14409
0
    ImGuiContext& g = *ctx;
14410
0
    for (ImGuiWindow* window : g.Windows)
14411
0
        window->SettingsOffset = -1;
14412
0
    g.SettingsWindows.clear();
14413
0
}
14414
14415
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14416
0
{
14417
0
    ImGuiID id = ImHashStr(name);
14418
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14419
0
    if (settings)
14420
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14421
0
    else
14422
0
        settings = ImGui::CreateNewWindowSettings(name);
14423
0
    settings->ID = id;
14424
0
    settings->WantApply = true;
14425
0
    return (void*)settings;
14426
0
}
14427
14428
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14429
0
{
14430
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14431
0
    int x, y;
14432
0
    int i;
14433
0
    ImU32 u1;
14434
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14435
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14436
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14437
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14438
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14439
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14440
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14441
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14442
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14443
0
}
14444
14445
// Apply to existing windows (if any)
14446
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14447
0
{
14448
0
    ImGuiContext& g = *ctx;
14449
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14450
0
        if (settings->WantApply)
14451
0
        {
14452
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14453
0
                ApplyWindowSettings(window, settings);
14454
0
            settings->WantApply = false;
14455
0
        }
14456
0
}
14457
14458
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14459
0
{
14460
    // Gather data from windows that were active during this session
14461
    // (if a window wasn't opened in this session we preserve its settings)
14462
0
    ImGuiContext& g = *ctx;
14463
0
    for (ImGuiWindow* window : g.Windows)
14464
0
    {
14465
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14466
0
            continue;
14467
14468
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14469
0
        if (!settings)
14470
0
        {
14471
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14472
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14473
0
        }
14474
0
        IM_ASSERT(settings->ID == window->ID);
14475
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14476
0
        settings->Size = ImVec2ih(window->SizeFull);
14477
0
        settings->ViewportId = window->ViewportId;
14478
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14479
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14480
0
        settings->DockId = window->DockId;
14481
0
        settings->ClassId = window->WindowClass.ClassId;
14482
0
        settings->DockOrder = window->DockOrder;
14483
0
        settings->Collapsed = window->Collapsed;
14484
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14485
0
        settings->WantDelete = false;
14486
0
    }
14487
14488
    // Write to text buffer
14489
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14490
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14491
0
    {
14492
0
        if (settings->WantDelete)
14493
0
            continue;
14494
0
        const char* settings_name = settings->GetName();
14495
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14496
0
        if (settings->IsChild)
14497
0
        {
14498
0
            buf->appendf("IsChild=1\n");
14499
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14500
0
        }
14501
0
        else
14502
0
        {
14503
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14504
0
            {
14505
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14506
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14507
0
            }
14508
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14509
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14510
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14511
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14512
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14513
0
            if (settings->DockId != 0)
14514
0
            {
14515
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14516
0
                if (settings->DockOrder == -1)
14517
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14518
0
                else
14519
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14520
0
                if (settings->ClassId != 0)
14521
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14522
0
            }
14523
0
        }
14524
0
        buf->append("\n");
14525
0
    }
14526
0
}
14527
14528
14529
//-----------------------------------------------------------------------------
14530
// [SECTION] LOCALIZATION
14531
//-----------------------------------------------------------------------------
14532
14533
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14534
1
{
14535
1
    ImGuiContext& g = *GImGui;
14536
12
    for (int n = 0; n < count; n++)
14537
11
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14538
1
}
14539
14540
14541
//-----------------------------------------------------------------------------
14542
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14543
//-----------------------------------------------------------------------------
14544
// - GetMainViewport()
14545
// - FindViewportByID()
14546
// - FindViewportByPlatformHandle()
14547
// - SetCurrentViewport() [Internal]
14548
// - SetWindowViewport() [Internal]
14549
// - GetWindowAlwaysWantOwnViewport() [Internal]
14550
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14551
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14552
// - TranslateWindowsInViewport() [Internal]
14553
// - ScaleWindowsInViewport() [Internal]
14554
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14555
// - UpdateViewportsNewFrame() [Internal]
14556
// - UpdateViewportsEndFrame() [Internal]
14557
// - AddUpdateViewport() [Internal]
14558
// - WindowSelectViewport() [Internal]
14559
// - WindowSyncOwnedViewport() [Internal]
14560
// - UpdatePlatformWindows()
14561
// - RenderPlatformWindowsDefault()
14562
// - FindPlatformMonitorForPos() [Internal]
14563
// - FindPlatformMonitorForRect() [Internal]
14564
// - UpdateViewportPlatformMonitor() [Internal]
14565
// - DestroyPlatformWindow() [Internal]
14566
// - DestroyPlatformWindows()
14567
//-----------------------------------------------------------------------------
14568
14569
ImGuiViewport* ImGui::GetMainViewport()
14570
89.2k
{
14571
89.2k
    ImGuiContext& g = *GImGui;
14572
89.2k
    return g.Viewports[0];
14573
89.2k
}
14574
14575
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14576
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14577
22.2k
{
14578
22.2k
    ImGuiContext& g = *GImGui;
14579
22.2k
    for (ImGuiViewportP* viewport : g.Viewports)
14580
22.2k
        if (viewport->ID == id)
14581
22.2k
            return viewport;
14582
0
    return NULL;
14583
22.2k
}
14584
14585
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14586
0
{
14587
0
    ImGuiContext& g = *GImGui;
14588
0
    for (ImGuiViewportP* viewport : g.Viewports)
14589
0
        if (viewport->PlatformHandle == platform_handle)
14590
0
            return viewport;
14591
0
    return NULL;
14592
0
}
14593
14594
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14595
89.7k
{
14596
89.7k
    ImGuiContext& g = *GImGui;
14597
89.7k
    (void)current_window;
14598
14599
89.7k
    if (viewport)
14600
67.4k
        viewport->LastFrameActive = g.FrameCount;
14601
89.7k
    if (g.CurrentViewport == viewport)
14602
45.2k
        return;
14603
44.4k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14604
44.4k
    g.CurrentViewport = viewport;
14605
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14606
14607
    // Notify platform layer of viewport changes
14608
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14609
44.4k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14610
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14611
44.4k
}
14612
14613
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14614
44.8k
{
14615
    // Abandon viewport
14616
44.8k
    if (window->ViewportOwned && window->Viewport->Window == window)
14617
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14618
14619
44.8k
    window->Viewport = viewport;
14620
44.8k
    window->ViewportId = viewport->ID;
14621
44.8k
    window->ViewportOwned = (viewport->Window == window);
14622
44.8k
}
14623
14624
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14625
0
{
14626
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14627
0
    ImGuiContext& g = *GImGui;
14628
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14629
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14630
0
            if (!window->DockIsActive)
14631
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14632
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14633
0
                        return true;
14634
0
    return false;
14635
0
}
14636
14637
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14638
0
{
14639
0
    ImGuiContext& g = *GImGui;
14640
0
    if (window->Viewport == viewport)
14641
0
        return false;
14642
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14643
0
        return false;
14644
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14645
0
        return false;
14646
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14647
0
        return false;
14648
0
    if (GetWindowAlwaysWantOwnViewport(window))
14649
0
        return false;
14650
14651
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14652
0
    for (ImGuiWindow* window_behind : g.Windows)
14653
0
    {
14654
0
        if (window_behind == window)
14655
0
            break;
14656
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14657
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14658
0
                return false;
14659
0
    }
14660
14661
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14662
0
    ImGuiViewportP* old_viewport = window->Viewport;
14663
0
    if (window->ViewportOwned)
14664
0
        for (int n = 0; n < g.Windows.Size; n++)
14665
0
            if (g.Windows[n]->Viewport == old_viewport)
14666
0
                SetWindowViewport(g.Windows[n], viewport);
14667
0
    SetWindowViewport(window, viewport);
14668
0
    BringWindowToDisplayFront(window);
14669
14670
0
    return true;
14671
0
}
14672
14673
// FIXME: handle 0 to N host viewports
14674
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14675
0
{
14676
0
    ImGuiContext& g = *GImGui;
14677
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14678
0
}
14679
14680
// Translate Dear ImGui windows when a Host Viewport has been moved
14681
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14682
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14683
0
{
14684
0
    ImGuiContext& g = *GImGui;
14685
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14686
14687
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14688
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14689
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14690
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14691
    // and so the window will appear to teleport when releasing the mouse.
14692
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14693
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14694
0
    ImVec2 delta_pos = new_pos - old_pos;
14695
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14696
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14697
0
            TranslateWindow(window, delta_pos);
14698
0
}
14699
14700
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14701
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14702
0
{
14703
0
    ImGuiContext& g = *GImGui;
14704
0
    if (viewport->Window)
14705
0
    {
14706
0
        ScaleWindow(viewport->Window, scale);
14707
0
    }
14708
0
    else
14709
0
    {
14710
0
        for (ImGuiWindow* window : g.Windows)
14711
0
            if (window->Viewport == viewport)
14712
0
                ScaleWindow(window, scale);
14713
0
    }
14714
0
}
14715
14716
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14717
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14718
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14719
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14720
0
{
14721
0
    ImGuiContext& g = *GImGui;
14722
0
    ImGuiViewportP* best_candidate = NULL;
14723
0
    for (ImGuiViewportP* viewport : g.Viewports)
14724
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14725
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14726
0
                best_candidate = viewport;
14727
0
    return best_candidate;
14728
0
}
14729
14730
// Update viewports and monitor infos
14731
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14732
static void ImGui::UpdateViewportsNewFrame()
14733
22.2k
{
14734
22.2k
    ImGuiContext& g = *GImGui;
14735
22.2k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14736
14737
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14738
    // Update Focused status
14739
22.2k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14740
22.2k
    if (viewports_enabled)
14741
0
    {
14742
0
        ImGuiViewportP* focused_viewport = NULL;
14743
0
        for (ImGuiViewportP* viewport : g.Viewports)
14744
0
        {
14745
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14746
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14747
0
            {
14748
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14749
0
                if (is_minimized)
14750
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14751
0
                else
14752
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14753
0
            }
14754
14755
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14756
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14757
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14758
0
            {
14759
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14760
0
                if (is_focused)
14761
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14762
0
                else
14763
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14764
0
                if (is_focused)
14765
0
                    focused_viewport = viewport;
14766
0
            }
14767
0
        }
14768
14769
        // Focused viewport has changed?
14770
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14771
0
        {
14772
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14773
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14774
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14775
14776
            // Store a tag so we can infer z-order easily from all our windows
14777
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14778
            // will keep the front most stamp instead of losing it back to their parent viewport.
14779
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14780
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14781
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14782
14783
            // Focus associated dear imgui window
14784
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14785
            // - if focus didn't happen because we destroyed another window (#6462)
14786
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14787
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14788
0
            if (apply_imgui_focus_on_focused_viewport)
14789
0
            {
14790
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14791
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14792
0
                if (focused_viewport->Window != NULL)
14793
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14794
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14795
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14796
0
                else
14797
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14798
0
            }
14799
0
        }
14800
0
        if (focused_viewport)
14801
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14802
0
    }
14803
14804
    // Create/update main viewport with current platform position.
14805
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14806
22.2k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14807
22.2k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14808
22.2k
    IM_ASSERT(main_viewport->Window == NULL);
14809
22.2k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14810
22.2k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14811
22.2k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14812
0
    {
14813
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14814
0
        main_viewport_size = main_viewport->Size;
14815
0
    }
14816
22.2k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14817
14818
22.2k
    g.CurrentDpiScale = 0.0f;
14819
22.2k
    g.CurrentViewport = NULL;
14820
22.2k
    g.MouseViewport = NULL;
14821
44.4k
    for (int n = 0; n < g.Viewports.Size; n++)
14822
22.2k
    {
14823
22.2k
        ImGuiViewportP* viewport = g.Viewports[n];
14824
22.2k
        viewport->Idx = n;
14825
14826
        // Erase unused viewports
14827
22.2k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14828
0
        {
14829
0
            DestroyViewport(viewport);
14830
0
            n--;
14831
0
            continue;
14832
0
        }
14833
14834
22.2k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14835
22.2k
        if (viewports_enabled)
14836
0
        {
14837
            // Update Position and Size (from Platform Window to ImGui) if requested.
14838
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14839
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14840
0
            {
14841
                // Viewport->WorkPos and WorkSize will be updated below
14842
0
                if (viewport->PlatformRequestMove)
14843
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14844
0
                if (viewport->PlatformRequestResize)
14845
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14846
0
            }
14847
0
        }
14848
14849
        // Update/copy monitor info
14850
22.2k
        UpdateViewportPlatformMonitor(viewport);
14851
14852
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14853
22.2k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14854
22.2k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14855
22.2k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14856
22.2k
        viewport->UpdateWorkRect();
14857
14858
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14859
22.2k
        viewport->Alpha = 1.0f;
14860
14861
        // Translate Dear ImGui windows when a Host Viewport has been moved
14862
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14863
22.2k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14864
22.2k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14865
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14866
14867
        // Update DPI scale
14868
22.2k
        float new_dpi_scale;
14869
22.2k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14870
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14871
22.2k
        else if (viewport->PlatformMonitor != -1)
14872
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14873
22.2k
        else
14874
22.2k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14875
22.2k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14876
0
        {
14877
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14878
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14879
0
                ScaleWindowsInViewport(viewport, scale_factor);
14880
            //if (viewport == GetMainViewport())
14881
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14882
14883
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14884
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14885
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14886
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14887
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14888
0
        }
14889
22.2k
        viewport->DpiScale = new_dpi_scale;
14890
22.2k
    }
14891
14892
    // Update fallback monitor
14893
22.2k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14894
22.2k
    if (g.PlatformIO.Monitors.Size == 0)
14895
22.2k
    {
14896
22.2k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14897
22.2k
        monitor->MainPos = main_viewport->Pos;
14898
22.2k
        monitor->MainSize = main_viewport->Size;
14899
22.2k
        monitor->WorkPos = main_viewport->WorkPos;
14900
22.2k
        monitor->WorkSize = main_viewport->WorkSize;
14901
22.2k
        monitor->DpiScale = main_viewport->DpiScale;
14902
22.2k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
14903
22.2k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
14904
22.2k
    }
14905
22.2k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
14906
0
    {
14907
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
14908
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
14909
0
    }
14910
14911
22.2k
    if (!viewports_enabled)
14912
22.2k
    {
14913
22.2k
        g.MouseViewport = main_viewport;
14914
22.2k
        return;
14915
22.2k
    }
14916
14917
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14918
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14919
0
    ImGuiViewportP* viewport_hovered = NULL;
14920
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14921
0
    {
14922
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14923
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14924
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14925
0
    }
14926
0
    else
14927
0
    {
14928
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14929
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14930
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14931
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14932
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14933
0
    }
14934
0
    if (viewport_hovered != NULL)
14935
0
        g.MouseLastHoveredViewport = viewport_hovered;
14936
0
    else if (g.MouseLastHoveredViewport == NULL)
14937
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14938
14939
    // Update mouse reference viewport
14940
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14941
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14942
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14943
0
        g.MouseViewport = g.MovingWindow->Viewport;
14944
0
    else
14945
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14946
14947
    // When dragging something, always refer to the last hovered viewport.
14948
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14949
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14950
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14951
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14952
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14953
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14954
0
        viewport_hovered = g.MouseLastHoveredViewport;
14955
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14956
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14957
0
            g.MouseViewport = viewport_hovered;
14958
14959
0
    IM_ASSERT(g.MouseViewport != NULL);
14960
0
}
14961
14962
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14963
static void ImGui::UpdateViewportsEndFrame()
14964
22.2k
{
14965
22.2k
    ImGuiContext& g = *GImGui;
14966
22.2k
    g.PlatformIO.Viewports.resize(0);
14967
44.4k
    for (int i = 0; i < g.Viewports.Size; i++)
14968
22.2k
    {
14969
22.2k
        ImGuiViewportP* viewport = g.Viewports[i];
14970
22.2k
        viewport->LastPos = viewport->Pos;
14971
22.2k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14972
0
            if (i > 0) // Always include main viewport in the list
14973
0
                continue;
14974
22.2k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14975
0
            continue;
14976
22.2k
        if (i > 0)
14977
22.2k
            IM_ASSERT(viewport->Window != NULL);
14978
22.2k
        g.PlatformIO.Viewports.push_back(viewport);
14979
22.2k
    }
14980
22.2k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14981
22.2k
}
14982
14983
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14984
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14985
22.2k
{
14986
22.2k
    ImGuiContext& g = *GImGui;
14987
22.2k
    IM_ASSERT(id != 0);
14988
14989
22.2k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14990
22.2k
    if (window != NULL)
14991
0
    {
14992
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14993
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14994
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14995
0
            flags |= ImGuiViewportFlags_NoInputs;
14996
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14997
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14998
0
    }
14999
15000
22.2k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15001
22.2k
    if (viewport)
15002
22.2k
    {
15003
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15004
22.2k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15005
22.2k
            viewport->Pos = pos;
15006
22.2k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15007
22.2k
            viewport->Size = size;
15008
22.2k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15009
22.2k
    }
15010
0
    else
15011
0
    {
15012
        // New viewport
15013
0
        viewport = IM_NEW(ImGuiViewportP)();
15014
0
        viewport->ID = id;
15015
0
        viewport->Idx = g.Viewports.Size;
15016
0
        viewport->Pos = viewport->LastPos = pos;
15017
0
        viewport->Size = size;
15018
0
        viewport->Flags = flags;
15019
0
        UpdateViewportPlatformMonitor(viewport);
15020
0
        g.Viewports.push_back(viewport);
15021
0
        g.ViewportCreatedCount++;
15022
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15023
15024
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15025
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15026
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15027
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15028
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15029
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15030
15031
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15032
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15033
0
        if (viewport->PlatformMonitor != -1)
15034
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15035
0
    }
15036
15037
22.2k
    viewport->Window = window;
15038
22.2k
    viewport->LastFrameActive = g.FrameCount;
15039
22.2k
    viewport->UpdateWorkRect();
15040
22.2k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15041
15042
22.2k
    if (window != NULL)
15043
0
        window->ViewportOwned = true;
15044
15045
22.2k
    return viewport;
15046
22.2k
}
15047
15048
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15049
0
{
15050
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15051
0
    ImGuiContext& g = *GImGui;
15052
0
    for (ImGuiWindow* window : g.Windows)
15053
0
    {
15054
0
        if (window->Viewport != viewport)
15055
0
            continue;
15056
0
        window->Viewport = NULL;
15057
0
        window->ViewportOwned = false;
15058
0
    }
15059
0
    if (viewport == g.MouseLastHoveredViewport)
15060
0
        g.MouseLastHoveredViewport = NULL;
15061
15062
    // Destroy
15063
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15064
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15065
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15066
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15067
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15068
0
    IM_DELETE(viewport);
15069
0
}
15070
15071
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15072
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15073
44.8k
{
15074
44.8k
    ImGuiContext& g = *GImGui;
15075
44.8k
    ImGuiWindowFlags flags = window->Flags;
15076
44.8k
    window->ViewportAllowPlatformMonitorExtend = -1;
15077
15078
    // Restore main viewport if multi-viewport is not supported by the backend
15079
44.8k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15080
44.8k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15081
44.8k
    {
15082
44.8k
        SetWindowViewport(window, main_viewport);
15083
44.8k
        return;
15084
44.8k
    }
15085
0
    window->ViewportOwned = false;
15086
15087
    // Appearing popups reset their viewport so they can inherit again
15088
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15089
0
    {
15090
0
        window->Viewport = NULL;
15091
0
        window->ViewportId = 0;
15092
0
    }
15093
15094
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15095
0
    {
15096
        // By default inherit from parent window
15097
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15098
0
            window->Viewport = window->ParentWindow->Viewport;
15099
15100
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15101
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15102
0
        {
15103
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15104
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15105
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15106
0
        }
15107
0
    }
15108
15109
0
    bool lock_viewport = false;
15110
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15111
0
    {
15112
        // Code explicitly request a viewport
15113
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15114
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15115
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15116
0
        {
15117
0
            window->Viewport->Window = window;
15118
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15119
0
        }
15120
0
        lock_viewport = true;
15121
0
    }
15122
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15123
0
    {
15124
        // Always inherit viewport from parent window
15125
0
        if (window->DockNode && window->DockNode->HostWindow)
15126
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15127
0
        window->Viewport = window->ParentWindow->Viewport;
15128
0
    }
15129
0
    else if (window->DockNode && window->DockNode->HostWindow)
15130
0
    {
15131
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15132
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15133
0
    }
15134
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15135
0
    {
15136
0
        window->Viewport = g.MouseViewport;
15137
0
    }
15138
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15139
0
    {
15140
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15141
0
    }
15142
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15143
0
    {
15144
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15145
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15146
0
    }
15147
0
    else
15148
0
    {
15149
        // Merge into host viewport?
15150
        // We cannot test window->ViewportOwned as it set lower in the function.
15151
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15152
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15153
0
        if (try_to_merge_into_host_viewport)
15154
0
            UpdateTryMergeWindowIntoHostViewports(window);
15155
0
    }
15156
15157
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15158
0
    if (window->Viewport == NULL)
15159
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15160
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15161
15162
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15163
0
    if (!lock_viewport)
15164
0
    {
15165
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15166
0
        {
15167
            // We need to take account of the possibility that mouse may become invalid.
15168
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15169
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15170
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15171
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15172
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15173
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15174
0
            else
15175
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15176
0
        }
15177
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15178
0
        {
15179
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15180
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15181
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15182
0
            {
15183
                // Steal/transfer ownership
15184
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15185
0
                window->Viewport->Window = window;
15186
0
                window->Viewport->ID = window->ID;
15187
0
                window->Viewport->LastNameHash = 0;
15188
0
            }
15189
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15190
0
            {
15191
                // New viewport
15192
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15193
0
            }
15194
0
        }
15195
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15196
0
        {
15197
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15198
            // Child windows are kept contained within their parent.
15199
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15200
0
        }
15201
0
    }
15202
15203
    // Update flags
15204
0
    window->ViewportOwned = (window == window->Viewport->Window);
15205
0
    window->ViewportId = window->Viewport->ID;
15206
15207
    // If the OS window has a title bar, hide our imgui title bar
15208
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15209
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15210
0
}
15211
15212
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15213
0
{
15214
0
    ImGuiContext& g = *GImGui;
15215
15216
0
    bool viewport_rect_changed = false;
15217
15218
    // Synchronize window --> viewport in most situations
15219
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15220
0
    if (window->Viewport->PlatformRequestMove)
15221
0
    {
15222
0
        window->Pos = window->Viewport->Pos;
15223
0
        MarkIniSettingsDirty(window);
15224
0
    }
15225
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15226
0
    {
15227
0
        viewport_rect_changed = true;
15228
0
        window->Viewport->Pos = window->Pos;
15229
0
    }
15230
15231
0
    if (window->Viewport->PlatformRequestResize)
15232
0
    {
15233
0
        window->Size = window->SizeFull = window->Viewport->Size;
15234
0
        MarkIniSettingsDirty(window);
15235
0
    }
15236
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15237
0
    {
15238
0
        viewport_rect_changed = true;
15239
0
        window->Viewport->Size = window->Size;
15240
0
    }
15241
0
    window->Viewport->UpdateWorkRect();
15242
15243
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15244
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15245
0
    if (viewport_rect_changed)
15246
0
        UpdateViewportPlatformMonitor(window->Viewport);
15247
15248
    // Update common viewport flags
15249
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15250
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15251
0
    ImGuiWindowFlags window_flags = window->Flags;
15252
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15253
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15254
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15255
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15256
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15257
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15258
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15259
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15260
15261
    // Not correct to set modal as topmost because:
15262
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15263
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15264
    //if (flags & ImGuiWindowFlags_Modal)
15265
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15266
15267
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15268
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15269
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15270
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15271
0
    if (is_short_lived_floating_window && !is_modal)
15272
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15273
15274
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15275
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15276
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15277
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15278
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15279
15280
    // We can also tell the backend that clearing the platform window won't be necessary,
15281
    // as our window background is filling the viewport and we have disabled BgAlpha.
15282
    // FIXME: Work on support for per-viewport transparency (#2766)
15283
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15284
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15285
15286
0
    window->Viewport->Flags = viewport_flags;
15287
15288
    // Update parent viewport ID
15289
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15290
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15291
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15292
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15293
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15294
0
    else
15295
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15296
0
}
15297
15298
// Called by user at the end of the main loop, after EndFrame()
15299
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15300
void ImGui::UpdatePlatformWindows()
15301
0
{
15302
0
    ImGuiContext& g = *GImGui;
15303
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15304
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15305
0
    g.FrameCountPlatformEnded = g.FrameCount;
15306
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15307
0
        return;
15308
15309
    // Create/resize/destroy platform windows to match each active viewport.
15310
    // Skip the main viewport (index 0), which is always fully handled by the application!
15311
0
    for (int i = 1; i < g.Viewports.Size; i++)
15312
0
    {
15313
0
        ImGuiViewportP* viewport = g.Viewports[i];
15314
15315
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15316
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15317
0
        bool destroy_platform_window = false;
15318
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15319
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15320
0
        if (destroy_platform_window)
15321
0
        {
15322
0
            DestroyPlatformWindow(viewport);
15323
0
            continue;
15324
0
        }
15325
15326
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15327
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15328
0
            continue;
15329
15330
        // Create window
15331
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15332
0
        if (is_new_platform_window)
15333
0
        {
15334
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15335
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15336
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15337
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15338
0
            g.PlatformWindowsCreatedCount++;
15339
0
            viewport->LastNameHash = 0;
15340
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15341
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15342
0
            viewport->PlatformWindowCreated = true;
15343
0
        }
15344
15345
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15346
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15347
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15348
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15349
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15350
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15351
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15352
0
        viewport->LastPlatformPos = viewport->Pos;
15353
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15354
15355
        // Update title bar (if it changed)
15356
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15357
0
        {
15358
0
            const char* title_begin = window_for_title->Name;
15359
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15360
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15361
0
            if (viewport->LastNameHash != title_hash)
15362
0
            {
15363
0
                char title_end_backup_c = *title_end;
15364
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15365
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15366
0
                *title_end = title_end_backup_c;
15367
0
                viewport->LastNameHash = title_hash;
15368
0
            }
15369
0
        }
15370
15371
        // Update alpha (if it changed)
15372
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15373
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15374
0
        viewport->LastAlpha = viewport->Alpha;
15375
15376
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15377
0
        if (g.PlatformIO.Platform_UpdateWindow)
15378
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15379
15380
0
        if (is_new_platform_window)
15381
0
        {
15382
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15383
0
            if (g.FrameCount < 3)
15384
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15385
15386
            // Show window
15387
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15388
15389
            // Even without focus, we assume the window becomes front-most.
15390
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15391
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15392
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15393
0
        }
15394
15395
        // Clear request flags
15396
0
        viewport->ClearRequestFlags();
15397
0
    }
15398
0
}
15399
15400
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15401
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15402
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15403
//
15404
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15405
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15406
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15407
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15408
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15409
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15410
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15411
//
15412
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15413
0
{
15414
    // Skip the main viewport (index 0), which is always fully handled by the application!
15415
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15416
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15417
0
    {
15418
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15419
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15420
0
            continue;
15421
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15422
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15423
0
    }
15424
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15425
0
    {
15426
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15427
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15428
0
            continue;
15429
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15430
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15431
0
    }
15432
0
}
15433
15434
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15435
0
{
15436
0
    ImGuiContext& g = *GImGui;
15437
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15438
0
    {
15439
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15440
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15441
0
            return monitor_n;
15442
0
    }
15443
0
    return -1;
15444
0
}
15445
15446
// Search for the monitor with the largest intersection area with the given rectangle
15447
// We generally try to avoid searching loops but the monitor count should be very small here
15448
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15449
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15450
22.2k
{
15451
22.2k
    ImGuiContext& g = *GImGui;
15452
15453
22.2k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15454
22.2k
    if (monitor_count <= 1)
15455
22.2k
        return monitor_count - 1;
15456
15457
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15458
    // This is necessary for tooltips which always resize down to zero at first.
15459
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15460
0
    int best_monitor_n = -1;
15461
0
    float best_monitor_surface = 0.001f;
15462
15463
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15464
0
    {
15465
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15466
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15467
0
        if (monitor_rect.Contains(rect))
15468
0
            return monitor_n;
15469
0
        ImRect overlapping_rect = rect;
15470
0
        overlapping_rect.ClipWithFull(monitor_rect);
15471
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15472
0
        if (overlapping_surface < best_monitor_surface)
15473
0
            continue;
15474
0
        best_monitor_surface = overlapping_surface;
15475
0
        best_monitor_n = monitor_n;
15476
0
    }
15477
0
    return best_monitor_n;
15478
0
}
15479
15480
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15481
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15482
22.2k
{
15483
22.2k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15484
22.2k
}
15485
15486
// Return value is always != NULL, but don't hold on it across frames.
15487
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15488
0
{
15489
0
    ImGuiContext& g = *GImGui;
15490
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15491
0
    int monitor_idx = viewport->PlatformMonitor;
15492
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15493
0
        return &g.PlatformIO.Monitors[monitor_idx];
15494
0
    return &g.FallbackMonitor;
15495
0
}
15496
15497
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15498
0
{
15499
0
    ImGuiContext& g = *GImGui;
15500
0
    if (viewport->PlatformWindowCreated)
15501
0
    {
15502
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15503
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15504
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15505
0
        if (g.PlatformIO.Platform_DestroyWindow)
15506
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15507
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15508
15509
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15510
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15511
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15512
0
            viewport->PlatformWindowCreated = false;
15513
0
    }
15514
0
    else
15515
0
    {
15516
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15517
0
    }
15518
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15519
0
    viewport->ClearRequestFlags();
15520
0
}
15521
15522
void ImGui::DestroyPlatformWindows()
15523
0
{
15524
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15525
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15526
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15527
    // code to operator a consistent manner.
15528
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15529
    // crashing if it doesn't have data stored.
15530
0
    ImGuiContext& g = *GImGui;
15531
0
    for (ImGuiViewportP* viewport : g.Viewports)
15532
0
        DestroyPlatformWindow(viewport);
15533
0
}
15534
15535
15536
//-----------------------------------------------------------------------------
15537
// [SECTION] DOCKING
15538
//-----------------------------------------------------------------------------
15539
// Docking: Internal Types
15540
// Docking: Forward Declarations
15541
// Docking: ImGuiDockContext
15542
// Docking: ImGuiDockContext Docking/Undocking functions
15543
// Docking: ImGuiDockNode
15544
// Docking: ImGuiDockNode Tree manipulation functions
15545
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15546
// Docking: Builder Functions
15547
// Docking: Begin/End Support Functions (called from Begin/End)
15548
// Docking: Settings
15549
//-----------------------------------------------------------------------------
15550
15551
//-----------------------------------------------------------------------------
15552
// Typical Docking call flow: (root level is generally public API):
15553
//-----------------------------------------------------------------------------
15554
// - NewFrame()                               new dear imgui frame
15555
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15556
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15557
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15558
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15559
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15560
//    | - DockContextProcessDock()            - process one docking request
15561
//    | - DockNodeUpdate()
15562
//    |   - DockNodeUpdateForRootNode()
15563
//    |     - DockNodeUpdateFlagsAndCollapse()
15564
//    |     - DockNodeFindInfo()
15565
//    |   - destroy unused node or tab bar
15566
//    |   - create dock node host window
15567
//    |      - Begin() etc.
15568
//    |   - DockNodeStartMouseMovingWindow()
15569
//    |   - DockNodeTreeUpdatePosSize()
15570
//    |   - DockNodeTreeUpdateSplitter()
15571
//    |   - draw node background
15572
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15573
//    |     - DockNodeAddTabBar()
15574
//    |     - DockNodeWindowMenuUpdate()
15575
//    |     - DockNodeCalcTabBarLayout()
15576
//    |     - BeginTabBarEx()
15577
//    |     - TabItemEx() calls
15578
//    |     - EndTabBar()
15579
//    |   - BeginDockableDragDropTarget()
15580
//    |      - DockNodeUpdate()               - recurse into child nodes...
15581
//-----------------------------------------------------------------------------
15582
// - DockSpace()                              user submit a dockspace into a window
15583
//    | Begin(Child)                          - create a child window
15584
//    | DockNodeUpdate()                      - call main dock node update function
15585
//    | End(Child)
15586
//    | ItemSize()
15587
//-----------------------------------------------------------------------------
15588
// - Begin()
15589
//    | BeginDocked()
15590
//    | BeginDockableDragDropSource()
15591
//    | BeginDockableDragDropTarget()
15592
//    | - DockNodePreviewDockRender()
15593
//-----------------------------------------------------------------------------
15594
// - EndFrame()
15595
//    | DockContextEndFrame()
15596
//-----------------------------------------------------------------------------
15597
15598
//-----------------------------------------------------------------------------
15599
// Docking: Internal Types
15600
//-----------------------------------------------------------------------------
15601
// - ImGuiDockRequestType
15602
// - ImGuiDockRequest
15603
// - ImGuiDockPreviewData
15604
// - ImGuiDockNodeSettings
15605
// - ImGuiDockContext
15606
//-----------------------------------------------------------------------------
15607
15608
enum ImGuiDockRequestType
15609
{
15610
    ImGuiDockRequestType_None = 0,
15611
    ImGuiDockRequestType_Dock,
15612
    ImGuiDockRequestType_Undock,
15613
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15614
};
15615
15616
struct ImGuiDockRequest
15617
{
15618
    ImGuiDockRequestType    Type;
15619
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15620
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15621
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15622
    ImGuiDir                DockSplitDir;
15623
    float                   DockSplitRatio;
15624
    bool                    DockSplitOuter;
15625
    ImGuiWindow*            UndockTargetWindow;
15626
    ImGuiDockNode*          UndockTargetNode;
15627
15628
    ImGuiDockRequest()
15629
0
    {
15630
0
        Type = ImGuiDockRequestType_None;
15631
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15632
0
        DockTargetNode = UndockTargetNode = NULL;
15633
0
        DockSplitDir = ImGuiDir_None;
15634
0
        DockSplitRatio = 0.5f;
15635
0
        DockSplitOuter = false;
15636
0
    }
15637
};
15638
15639
struct ImGuiDockPreviewData
15640
{
15641
    ImGuiDockNode   FutureNode;
15642
    bool            IsDropAllowed;
15643
    bool            IsCenterAvailable;
15644
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15645
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15646
    ImGuiDockNode*  SplitNode;
15647
    ImGuiDir        SplitDir;
15648
    float           SplitRatio;
15649
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15650
15651
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15652
};
15653
15654
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15655
struct ImGuiDockNodeSettings
15656
{
15657
    ImGuiID             ID;
15658
    ImGuiID             ParentNodeId;
15659
    ImGuiID             ParentWindowId;
15660
    ImGuiID             SelectedTabId;
15661
    signed char         SplitAxis;
15662
    char                Depth;
15663
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15664
    ImVec2ih            Pos;
15665
    ImVec2ih            Size;
15666
    ImVec2ih            SizeRef;
15667
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15668
};
15669
15670
//-----------------------------------------------------------------------------
15671
// Docking: Forward Declarations
15672
//-----------------------------------------------------------------------------
15673
15674
namespace ImGui
15675
{
15676
    // ImGuiDockContext
15677
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15678
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15679
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15680
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15681
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15682
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15683
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15684
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15685
15686
    // ImGuiDockNode
15687
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15688
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15689
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15690
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15691
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15692
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15693
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15694
    static void             DockNodeUpdate(ImGuiDockNode* node);
15695
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15696
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15697
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15698
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15699
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15700
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15701
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15702
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15703
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15704
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15705
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15706
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15707
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15708
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15709
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15710
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15711
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15712
15713
    // ImGuiDockNode tree manipulations
15714
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15715
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15716
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15717
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15718
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15719
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15720
15721
    // Settings
15722
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15723
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15724
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15725
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15726
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15727
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15728
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15729
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15730
}
15731
15732
//-----------------------------------------------------------------------------
15733
// Docking: ImGuiDockContext
15734
//-----------------------------------------------------------------------------
15735
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15736
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15737
// At boot time only, we run a simple GC to remove nodes that have no references.
15738
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15739
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15740
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15741
//-----------------------------------------------------------------------------
15742
// - DockContextInitialize()
15743
// - DockContextShutdown()
15744
// - DockContextClearNodes()
15745
// - DockContextRebuildNodes()
15746
// - DockContextNewFrameUpdateUndocking()
15747
// - DockContextNewFrameUpdateDocking()
15748
// - DockContextEndFrame()
15749
// - DockContextFindNodeByID()
15750
// - DockContextBindNodeToWindow()
15751
// - DockContextGenNodeID()
15752
// - DockContextAddNode()
15753
// - DockContextRemoveNode()
15754
// - ImGuiDockContextPruneNodeData
15755
// - DockContextPruneUnusedSettingsNodes()
15756
// - DockContextBuildNodesFromSettings()
15757
// - DockContextBuildAddWindowsToNodes()
15758
//-----------------------------------------------------------------------------
15759
15760
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15761
1
{
15762
1
    ImGuiContext& g = *ctx;
15763
15764
    // Add .ini handle for persistent docking data
15765
1
    ImGuiSettingsHandler ini_handler;
15766
1
    ini_handler.TypeName = "Docking";
15767
1
    ini_handler.TypeHash = ImHashStr("Docking");
15768
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15769
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15770
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15771
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15772
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15773
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15774
1
    g.SettingsHandlers.push_back(ini_handler);
15775
15776
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15777
1
}
15778
15779
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15780
0
{
15781
0
    ImGuiDockContext* dc = &ctx->DockContext;
15782
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15783
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15784
0
            IM_DELETE(node);
15785
0
}
15786
15787
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15788
0
{
15789
0
    IM_UNUSED(ctx);
15790
0
    IM_ASSERT(ctx == GImGui);
15791
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15792
0
    DockBuilderRemoveNodeChildNodes(root_id);
15793
0
}
15794
15795
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15796
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15797
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15798
0
{
15799
0
    ImGuiContext& g = *ctx;
15800
0
    ImGuiDockContext* dc = &ctx->DockContext;
15801
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15802
0
    SaveIniSettingsToMemory();
15803
0
    ImGuiID root_id = 0; // Rebuild all
15804
0
    DockContextClearNodes(ctx, root_id, false);
15805
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15806
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15807
0
}
15808
15809
// Docking context update function, called by NewFrame()
15810
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15811
22.2k
{
15812
22.2k
    ImGuiContext& g = *ctx;
15813
22.2k
    ImGuiDockContext* dc = &ctx->DockContext;
15814
22.2k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15815
0
    {
15816
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15817
0
            DockContextClearNodes(ctx, 0, true);
15818
0
        return;
15819
0
    }
15820
15821
    // Setting NoSplit at runtime merges all nodes
15822
22.2k
    if (g.IO.ConfigDockingNoSplit)
15823
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15824
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15825
0
                if (node->IsRootNode() && node->IsSplitNode())
15826
0
                {
15827
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15828
                    //dc->WantFullRebuild = true;
15829
0
                }
15830
15831
    // Process full rebuild
15832
#if 0
15833
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15834
        dc->WantFullRebuild = true;
15835
#endif
15836
22.2k
    if (dc->WantFullRebuild)
15837
0
    {
15838
0
        DockContextRebuildNodes(ctx);
15839
0
        dc->WantFullRebuild = false;
15840
0
    }
15841
15842
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15843
22.2k
    for (ImGuiDockRequest& req : dc->Requests)
15844
0
    {
15845
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15846
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15847
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15848
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15849
0
    }
15850
22.2k
}
15851
15852
// Docking context update function, called by NewFrame()
15853
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15854
22.2k
{
15855
22.2k
    ImGuiContext& g = *ctx;
15856
22.2k
    ImGuiDockContext* dc = &ctx->DockContext;
15857
22.2k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15858
0
        return;
15859
15860
    // [DEBUG] Store hovered dock node.
15861
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15862
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15863
22.2k
    g.DebugHoveredDockNode = NULL;
15864
22.2k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15865
1.10k
    {
15866
1.10k
        if (hovered_window->DockNodeAsHost)
15867
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15868
1.10k
        else if (hovered_window->RootWindow->DockNode)
15869
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15870
1.10k
    }
15871
15872
    // Process Docking requests
15873
22.2k
    for (ImGuiDockRequest& req : dc->Requests)
15874
0
        if (req.Type == ImGuiDockRequestType_Dock)
15875
0
            DockContextProcessDock(ctx, &req);
15876
22.2k
    dc->Requests.resize(0);
15877
15878
    // Create windows for each automatic docking nodes
15879
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15880
22.2k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15881
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15882
0
            if (node->IsFloatingNode())
15883
0
                DockNodeUpdate(node);
15884
22.2k
}
15885
15886
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15887
22.2k
{
15888
    // Draw backgrounds of node missing their window
15889
22.2k
    ImGuiContext& g = *ctx;
15890
22.2k
    ImGuiDockContext* dc = &g.DockContext;
15891
22.2k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15892
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15893
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15894
0
            {
15895
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15896
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15897
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15898
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15899
0
            }
15900
22.2k
}
15901
15902
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15903
0
{
15904
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15905
0
}
15906
15907
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15908
0
{
15909
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15910
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15911
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15912
0
    ImGuiID id = 0x0001;
15913
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15914
0
        id++;
15915
0
    return id;
15916
0
}
15917
15918
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15919
0
{
15920
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15921
0
    ImGuiContext& g = *ctx;
15922
0
    if (id == 0)
15923
0
        id = DockContextGenNodeID(ctx);
15924
0
    else
15925
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15926
15927
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15928
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15929
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15930
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15931
0
    return node;
15932
0
}
15933
15934
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15935
0
{
15936
0
    ImGuiContext& g = *ctx;
15937
0
    ImGuiDockContext* dc = &ctx->DockContext;
15938
15939
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15940
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15941
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15942
0
    IM_ASSERT(node->Windows.Size == 0);
15943
15944
0
    if (node->HostWindow)
15945
0
        node->HostWindow->DockNodeAsHost = NULL;
15946
15947
0
    ImGuiDockNode* parent_node = node->ParentNode;
15948
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15949
0
    if (merge)
15950
0
    {
15951
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15952
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15953
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15954
0
    }
15955
0
    else
15956
0
    {
15957
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15958
0
            if (parent_node->ChildNodes[n] == node)
15959
0
                node->ParentNode->ChildNodes[n] = NULL;
15960
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15961
0
        IM_DELETE(node);
15962
0
    }
15963
0
}
15964
15965
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15966
0
{
15967
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15968
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15969
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15970
0
}
15971
15972
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15973
struct ImGuiDockContextPruneNodeData
15974
{
15975
    int         CountWindows, CountChildWindows, CountChildNodes;
15976
    ImGuiID     RootId;
15977
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15978
};
15979
15980
// Garbage collect unused nodes (run once at init time)
15981
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15982
0
{
15983
0
    ImGuiContext& g = *ctx;
15984
0
    ImGuiDockContext* dc = &ctx->DockContext;
15985
0
    IM_ASSERT(g.Windows.Size == 0);
15986
15987
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15988
0
    pool.Reserve(dc->NodesSettings.Size);
15989
15990
    // Count child nodes and compute RootID
15991
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15992
0
    {
15993
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15994
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15995
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15996
0
        if (settings->ParentNodeId)
15997
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15998
0
    }
15999
16000
    // Count reference to dock ids from dockspaces
16001
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16002
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16003
0
    {
16004
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16005
0
        if (settings->ParentWindowId != 0)
16006
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16007
0
                if (window_settings->DockId)
16008
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16009
0
                        data->CountChildNodes++;
16010
0
    }
16011
16012
    // Count reference to dock ids from window settings
16013
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16014
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16015
0
        if (ImGuiID dock_id = settings->DockId)
16016
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16017
0
            {
16018
0
                data->CountWindows++;
16019
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16020
0
                    data_root->CountChildWindows++;
16021
0
            }
16022
16023
    // Prune
16024
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16025
0
    {
16026
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16027
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16028
0
        if (data->CountWindows > 1)
16029
0
            continue;
16030
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16031
16032
0
        bool remove = false;
16033
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16034
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16035
0
        remove |= (data_root->CountChildWindows == 0);
16036
0
        if (remove)
16037
0
        {
16038
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16039
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16040
0
            settings->ID = 0;
16041
0
        }
16042
0
    }
16043
0
}
16044
16045
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16046
0
{
16047
    // Build nodes
16048
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16049
0
    {
16050
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16051
0
        if (settings->ID == 0)
16052
0
            continue;
16053
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16054
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16055
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16056
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16057
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16058
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16059
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16060
0
            node->ParentNode->ChildNodes[0] = node;
16061
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16062
0
            node->ParentNode->ChildNodes[1] = node;
16063
0
        node->SelectedTabId = settings->SelectedTabId;
16064
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16065
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16066
16067
        // Bind host window immediately if it already exist (in case of a rebuild)
16068
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16069
0
        char host_window_title[20];
16070
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16071
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16072
0
    }
16073
0
}
16074
16075
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16076
0
{
16077
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16078
0
    ImGuiContext& g = *ctx;
16079
0
    for (ImGuiWindow* window : g.Windows)
16080
0
    {
16081
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16082
0
            continue;
16083
0
        if (window->DockNode != NULL)
16084
0
            continue;
16085
16086
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16087
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16088
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16089
0
            DockNodeAddWindow(node, window, true);
16090
0
    }
16091
0
}
16092
16093
//-----------------------------------------------------------------------------
16094
// Docking: ImGuiDockContext Docking/Undocking functions
16095
//-----------------------------------------------------------------------------
16096
// - DockContextQueueDock()
16097
// - DockContextQueueUndockWindow()
16098
// - DockContextQueueUndockNode()
16099
// - DockContextQueueNotifyRemovedNode()
16100
// - DockContextProcessDock()
16101
// - DockContextProcessUndockWindow()
16102
// - DockContextProcessUndockNode()
16103
// - DockContextCalcDropPosForDocking()
16104
//-----------------------------------------------------------------------------
16105
16106
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16107
0
{
16108
0
    IM_ASSERT(target != payload);
16109
0
    ImGuiDockRequest req;
16110
0
    req.Type = ImGuiDockRequestType_Dock;
16111
0
    req.DockTargetWindow = target;
16112
0
    req.DockTargetNode = target_node;
16113
0
    req.DockPayload = payload;
16114
0
    req.DockSplitDir = split_dir;
16115
0
    req.DockSplitRatio = split_ratio;
16116
0
    req.DockSplitOuter = split_outer;
16117
0
    ctx->DockContext.Requests.push_back(req);
16118
0
}
16119
16120
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16121
0
{
16122
0
    ImGuiDockRequest req;
16123
0
    req.Type = ImGuiDockRequestType_Undock;
16124
0
    req.UndockTargetWindow = window;
16125
0
    ctx->DockContext.Requests.push_back(req);
16126
0
}
16127
16128
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16129
0
{
16130
0
    ImGuiDockRequest req;
16131
0
    req.Type = ImGuiDockRequestType_Undock;
16132
0
    req.UndockTargetNode = node;
16133
0
    ctx->DockContext.Requests.push_back(req);
16134
0
}
16135
16136
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16137
0
{
16138
0
    ImGuiDockContext* dc = &ctx->DockContext;
16139
0
    for (ImGuiDockRequest& req : dc->Requests)
16140
0
        if (req.DockTargetNode == node)
16141
0
            req.Type = ImGuiDockRequestType_None;
16142
0
}
16143
16144
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16145
0
{
16146
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16147
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16148
16149
0
    ImGuiContext& g = *ctx;
16150
0
    IM_UNUSED(g);
16151
16152
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16153
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16154
0
    ImGuiDockNode* node = req->DockTargetNode;
16155
0
    if (payload_window)
16156
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16157
0
    else
16158
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16159
16160
    // Decide which Tab will be selected at the end of the operation
16161
0
    ImGuiID next_selected_id = 0;
16162
0
    ImGuiDockNode* payload_node = NULL;
16163
0
    if (payload_window)
16164
0
    {
16165
0
        payload_node = payload_window->DockNodeAsHost;
16166
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16167
0
        if (payload_node && payload_node->IsLeafNode())
16168
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16169
0
        if (payload_node == NULL)
16170
0
            next_selected_id = payload_window->TabId;
16171
0
    }
16172
16173
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16174
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16175
0
    if (node)
16176
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16177
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16178
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16179
16180
    // Create new node and add existing window to it
16181
0
    if (node == NULL)
16182
0
    {
16183
0
        node = DockContextAddNode(ctx, 0);
16184
0
        node->Pos = target_window->Pos;
16185
0
        node->Size = target_window->Size;
16186
0
        if (target_window->DockNodeAsHost == NULL)
16187
0
        {
16188
0
            DockNodeAddWindow(node, target_window, true);
16189
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16190
0
            target_window->DockIsActive = true;
16191
0
        }
16192
0
    }
16193
16194
0
    ImGuiDir split_dir = req->DockSplitDir;
16195
0
    if (split_dir != ImGuiDir_None)
16196
0
    {
16197
        // Split into two, one side will be our payload node unless we are dropping a loose window
16198
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16199
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16200
0
        const float split_ratio = req->DockSplitRatio;
16201
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16202
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16203
0
        new_node->HostWindow = node->HostWindow;
16204
0
        node = new_node;
16205
0
    }
16206
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16207
16208
0
    if (node != payload_node)
16209
0
    {
16210
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16211
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16212
0
        {
16213
0
            DockNodeAddTabBar(node);
16214
0
            for (int n = 0; n < node->Windows.Size; n++)
16215
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16216
0
        }
16217
16218
0
        if (payload_node != NULL)
16219
0
        {
16220
            // Transfer full payload node (with 1+ child windows or child nodes)
16221
0
            if (payload_node->IsSplitNode())
16222
0
            {
16223
0
                if (node->Windows.Size > 0)
16224
0
                {
16225
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16226
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16227
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16228
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16229
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16230
0
                    if (visible_node->TabBar)
16231
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16232
0
                    DockNodeMoveWindows(node, visible_node);
16233
0
                    DockNodeMoveWindows(visible_node, node);
16234
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16235
0
                }
16236
0
                if (node->IsCentralNode())
16237
0
                {
16238
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16239
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16240
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16241
0
                    IM_ASSERT(last_focused_node != NULL);
16242
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16243
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16244
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16245
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16246
0
                    last_focused_root_node->CentralNode = last_focused_node;
16247
0
                }
16248
16249
0
                IM_ASSERT(node->Windows.Size == 0);
16250
0
                DockNodeMoveChildNodes(node, payload_node);
16251
0
            }
16252
0
            else
16253
0
            {
16254
0
                const ImGuiID payload_dock_id = payload_node->ID;
16255
0
                DockNodeMoveWindows(node, payload_node);
16256
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16257
0
            }
16258
0
            DockContextRemoveNode(ctx, payload_node, true);
16259
0
        }
16260
0
        else if (payload_window)
16261
0
        {
16262
            // Transfer single window
16263
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16264
0
            node->VisibleWindow = payload_window;
16265
0
            DockNodeAddWindow(node, payload_window, true);
16266
0
            if (payload_dock_id != 0)
16267
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16268
0
        }
16269
0
    }
16270
0
    else
16271
0
    {
16272
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16273
0
        node->WantHiddenTabBarUpdate = true;
16274
0
    }
16275
16276
    // Update selection immediately
16277
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16278
0
        tab_bar->NextSelectedTabId = next_selected_id;
16279
0
    MarkIniSettingsDirty();
16280
0
}
16281
16282
// Problem:
16283
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16284
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16285
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16286
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16287
// Solution:
16288
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16289
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16290
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16291
0
{
16292
0
    if (ref_viewport == NULL)
16293
0
        return size;
16294
16295
0
    ImGuiContext& g = *GImGui;
16296
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16297
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16298
0
    {
16299
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16300
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16301
0
    }
16302
0
    return ImMin(size, max_size);
16303
0
}
16304
16305
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16306
0
{
16307
0
    ImGuiContext& g = *ctx;
16308
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16309
0
    if (window->DockNode)
16310
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16311
0
    else
16312
0
        window->DockId = 0;
16313
0
    window->Collapsed = false;
16314
0
    window->DockIsActive = false;
16315
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16316
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16317
16318
0
    MarkIniSettingsDirty();
16319
0
}
16320
16321
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16322
0
{
16323
0
    ImGuiContext& g = *ctx;
16324
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16325
0
    IM_ASSERT(node->IsLeafNode());
16326
0
    IM_ASSERT(node->Windows.Size >= 1);
16327
16328
0
    if (node->IsRootNode() || node->IsCentralNode())
16329
0
    {
16330
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16331
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16332
0
        new_node->Pos = node->Pos;
16333
0
        new_node->Size = node->Size;
16334
0
        new_node->SizeRef = node->SizeRef;
16335
0
        DockNodeMoveWindows(new_node, node);
16336
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16337
0
        node = new_node;
16338
0
    }
16339
0
    else
16340
0
    {
16341
        // Otherwise extract our node and merge our sibling back into the parent node.
16342
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16343
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16344
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16345
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16346
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16347
0
        node->ParentNode = NULL;
16348
0
    }
16349
0
    for (ImGuiWindow* window : node->Windows)
16350
0
    {
16351
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16352
0
        if (window->ParentWindow)
16353
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16354
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16355
0
    }
16356
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16357
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16358
0
    node->WantMouseMove = true;
16359
0
    MarkIniSettingsDirty();
16360
0
}
16361
16362
// This is mostly used for automation.
16363
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16364
0
{
16365
0
    if (target != NULL && target_node == NULL)
16366
0
        target_node = target->DockNode;
16367
16368
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16369
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16370
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16371
0
        split_outer = true;
16372
0
    ImGuiDockPreviewData split_data;
16373
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16374
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16375
0
        return false;
16376
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16377
0
    return true;
16378
0
}
16379
16380
//-----------------------------------------------------------------------------
16381
// Docking: ImGuiDockNode
16382
//-----------------------------------------------------------------------------
16383
// - DockNodeGetTabOrder()
16384
// - DockNodeAddWindow()
16385
// - DockNodeRemoveWindow()
16386
// - DockNodeMoveChildNodes()
16387
// - DockNodeMoveWindows()
16388
// - DockNodeApplyPosSizeToWindows()
16389
// - DockNodeHideHostWindow()
16390
// - ImGuiDockNodeFindInfoResults
16391
// - DockNodeFindInfo()
16392
// - DockNodeFindWindowByID()
16393
// - DockNodeUpdateFlagsAndCollapse()
16394
// - DockNodeUpdateHasCentralNodeFlag()
16395
// - DockNodeUpdateVisibleFlag()
16396
// - DockNodeStartMouseMovingWindow()
16397
// - DockNodeUpdate()
16398
// - DockNodeUpdateWindowMenu()
16399
// - DockNodeBeginAmendTabBar()
16400
// - DockNodeEndAmendTabBar()
16401
// - DockNodeUpdateTabBar()
16402
// - DockNodeAddTabBar()
16403
// - DockNodeRemoveTabBar()
16404
// - DockNodeIsDropAllowedOne()
16405
// - DockNodeIsDropAllowed()
16406
// - DockNodeCalcTabBarLayout()
16407
// - DockNodeCalcSplitRects()
16408
// - DockNodeCalcDropRectsAndTestMousePos()
16409
// - DockNodePreviewDockSetup()
16410
// - DockNodePreviewDockRender()
16411
//-----------------------------------------------------------------------------
16412
16413
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16414
0
{
16415
0
    ID = id;
16416
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16417
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16418
0
    TabBar = NULL;
16419
0
    SplitAxis = ImGuiAxis_None;
16420
16421
0
    State = ImGuiDockNodeState_Unknown;
16422
0
    LastBgColor = IM_COL32_WHITE;
16423
0
    HostWindow = VisibleWindow = NULL;
16424
0
    CentralNode = OnlyNodeWithWindows = NULL;
16425
0
    CountNodeWithWindows = 0;
16426
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16427
0
    LastFocusedNodeId = 0;
16428
0
    SelectedTabId = 0;
16429
0
    WantCloseTabId = 0;
16430
0
    RefViewportId = 0;
16431
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16432
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16433
0
    IsVisible = true;
16434
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16435
0
    IsBgDrawnThisFrame = false;
16436
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16437
0
}
16438
16439
ImGuiDockNode::~ImGuiDockNode()
16440
0
{
16441
0
    IM_DELETE(TabBar);
16442
0
    TabBar = NULL;
16443
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16444
0
}
16445
16446
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16447
0
{
16448
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16449
0
    if (tab_bar == NULL)
16450
0
        return -1;
16451
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16452
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16453
0
}
16454
16455
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16456
0
{
16457
0
    window->Hidden = true;
16458
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16459
0
}
16460
16461
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16462
0
{
16463
0
    ImGuiContext& g = *GImGui; (void)g;
16464
0
    if (window->DockNode)
16465
0
    {
16466
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16467
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16468
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16469
0
    }
16470
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16471
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16472
16473
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16474
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16475
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16476
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16477
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16478
16479
0
    node->Windows.push_back(window);
16480
0
    node->WantHiddenTabBarUpdate = true;
16481
0
    window->DockNode = node;
16482
0
    window->DockId = node->ID;
16483
0
    window->DockIsActive = (node->Windows.Size > 1);
16484
0
    window->DockTabWantClose = false;
16485
16486
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16487
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16488
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16489
0
    {
16490
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16491
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16492
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16493
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16494
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16495
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16496
0
    }
16497
16498
    // Add to tab bar if requested
16499
0
    if (add_to_tab_bar)
16500
0
    {
16501
0
        if (node->TabBar == NULL)
16502
0
        {
16503
0
            DockNodeAddTabBar(node);
16504
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16505
16506
            // Add existing windows
16507
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16508
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16509
0
        }
16510
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16511
0
    }
16512
16513
0
    DockNodeUpdateVisibleFlag(node);
16514
16515
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16516
0
    if (node->HostWindow)
16517
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16518
0
}
16519
16520
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16521
0
{
16522
0
    ImGuiContext& g = *GImGui;
16523
0
    IM_ASSERT(window->DockNode == node);
16524
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16525
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16526
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16527
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16528
16529
0
    window->DockNode = NULL;
16530
0
    window->DockIsActive = window->DockTabWantClose = false;
16531
0
    window->DockId = save_dock_id;
16532
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16533
0
    if (window->ParentWindow)
16534
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16535
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16536
16537
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16538
0
    {
16539
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16540
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16541
0
        window->Viewport = NULL;
16542
0
        window->ViewportId = 0;
16543
0
        window->ViewportOwned = false;
16544
0
        window->Hidden = true;
16545
0
    }
16546
16547
    // Remove window
16548
0
    bool erased = false;
16549
0
    for (int n = 0; n < node->Windows.Size; n++)
16550
0
        if (node->Windows[n] == window)
16551
0
        {
16552
0
            node->Windows.erase(node->Windows.Data + n);
16553
0
            erased = true;
16554
0
            break;
16555
0
        }
16556
0
    if (!erased)
16557
0
        IM_ASSERT(erased);
16558
0
    if (node->VisibleWindow == window)
16559
0
        node->VisibleWindow = NULL;
16560
16561
    // Remove tab and possibly tab bar
16562
0
    node->WantHiddenTabBarUpdate = true;
16563
0
    if (node->TabBar)
16564
0
    {
16565
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16566
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16567
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16568
0
            DockNodeRemoveTabBar(node);
16569
0
    }
16570
16571
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16572
0
    {
16573
        // Automatic dock node delete themselves if they are not holding at least one tab
16574
0
        DockContextRemoveNode(&g, node, true);
16575
0
        return;
16576
0
    }
16577
16578
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16579
0
    {
16580
0
        ImGuiWindow* remaining_window = node->Windows[0];
16581
        // Note: we used to transport viewport ownership here.
16582
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16583
0
    }
16584
16585
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16586
0
    DockNodeUpdateVisibleFlag(node);
16587
0
}
16588
16589
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16590
0
{
16591
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16592
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16593
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16594
0
    if (dst_node->ChildNodes[0])
16595
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16596
0
    if (dst_node->ChildNodes[1])
16597
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16598
0
    dst_node->SplitAxis = src_node->SplitAxis;
16599
0
    dst_node->SizeRef = src_node->SizeRef;
16600
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16601
0
}
16602
16603
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16604
0
{
16605
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16606
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16607
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16608
0
    if (src_tab_bar != NULL)
16609
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16610
16611
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16612
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16613
0
    if (move_tab_bar)
16614
0
    {
16615
0
        dst_node->TabBar = src_node->TabBar;
16616
0
        src_node->TabBar = NULL;
16617
0
    }
16618
16619
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16620
0
    for (ImGuiWindow* window : src_node->Windows)
16621
0
    {
16622
0
        window->DockNode = NULL;
16623
0
        window->DockIsActive = false;
16624
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16625
0
    }
16626
0
    src_node->Windows.clear();
16627
16628
0
    if (!move_tab_bar && src_node->TabBar)
16629
0
    {
16630
0
        if (dst_node->TabBar)
16631
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16632
0
        DockNodeRemoveTabBar(src_node);
16633
0
    }
16634
0
}
16635
16636
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16637
0
{
16638
0
    for (ImGuiWindow* window : node->Windows)
16639
0
    {
16640
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16641
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16642
0
    }
16643
0
}
16644
16645
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16646
0
{
16647
0
    if (node->HostWindow)
16648
0
    {
16649
0
        if (node->HostWindow->DockNodeAsHost == node)
16650
0
            node->HostWindow->DockNodeAsHost = NULL;
16651
0
        node->HostWindow = NULL;
16652
0
    }
16653
16654
0
    if (node->Windows.Size == 1)
16655
0
    {
16656
0
        node->VisibleWindow = node->Windows[0];
16657
0
        node->Windows[0]->DockIsActive = false;
16658
0
    }
16659
16660
0
    if (node->TabBar)
16661
0
        DockNodeRemoveTabBar(node);
16662
0
}
16663
16664
// Search function called once by root node in DockNodeUpdate()
16665
struct ImGuiDockNodeTreeInfo
16666
{
16667
    ImGuiDockNode*      CentralNode;
16668
    ImGuiDockNode*      FirstNodeWithWindows;
16669
    int                 CountNodesWithWindows;
16670
    //ImGuiWindowClass  WindowClassForMerges;
16671
16672
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16673
};
16674
16675
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16676
0
{
16677
0
    if (node->Windows.Size > 0)
16678
0
    {
16679
0
        if (info->FirstNodeWithWindows == NULL)
16680
0
            info->FirstNodeWithWindows = node;
16681
0
        info->CountNodesWithWindows++;
16682
0
    }
16683
0
    if (node->IsCentralNode())
16684
0
    {
16685
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16686
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16687
0
        info->CentralNode = node;
16688
0
    }
16689
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16690
0
        return;
16691
0
    if (node->ChildNodes[0])
16692
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16693
0
    if (node->ChildNodes[1])
16694
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16695
0
}
16696
16697
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16698
0
{
16699
0
    IM_ASSERT(id != 0);
16700
0
    for (ImGuiWindow* window : node->Windows)
16701
0
        if (window->ID == id)
16702
0
            return window;
16703
0
    return NULL;
16704
0
}
16705
16706
// - Remove inactive windows/nodes.
16707
// - Update visibility flag.
16708
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16709
0
{
16710
0
    ImGuiContext& g = *GImGui;
16711
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16712
16713
    // Inherit most flags
16714
0
    if (node->ParentNode)
16715
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16716
16717
    // Recurse into children
16718
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16719
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16720
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16721
0
    node->HasCentralNodeChild = false;
16722
0
    if (node->ChildNodes[0])
16723
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16724
0
    if (node->ChildNodes[1])
16725
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16726
16727
    // Remove inactive windows, collapse nodes
16728
    // Merge node flags overrides stored in windows
16729
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16730
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16731
0
    {
16732
0
        ImGuiWindow* window = node->Windows[window_n];
16733
0
        IM_ASSERT(window->DockNode == node);
16734
16735
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16736
0
        bool remove = false;
16737
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16738
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16739
0
        remove |= (window->DockTabWantClose);
16740
0
        if (remove)
16741
0
        {
16742
0
            window->DockTabWantClose = false;
16743
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16744
0
            {
16745
0
                DockNodeHideHostWindow(node);
16746
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16747
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16748
0
                return;
16749
0
            }
16750
0
            DockNodeRemoveWindow(node, window, node->ID);
16751
0
            window_n--;
16752
0
            continue;
16753
0
        }
16754
16755
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16756
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16757
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16758
0
    }
16759
0
    node->UpdateMergedFlags();
16760
16761
    // Auto-hide tab bar option
16762
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16763
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16764
0
        node->WantHiddenTabBarToggle = true;
16765
0
    node->WantHiddenTabBarUpdate = false;
16766
16767
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16768
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16769
0
        node->WantHiddenTabBarToggle = false;
16770
16771
    // Apply toggles at a single point of the frame (here!)
16772
0
    if (node->Windows.Size > 1)
16773
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16774
0
    else if (node->WantHiddenTabBarToggle)
16775
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16776
0
    node->WantHiddenTabBarToggle = false;
16777
16778
0
    DockNodeUpdateVisibleFlag(node);
16779
0
}
16780
16781
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16782
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16783
0
{
16784
0
    node->HasCentralNodeChild = false;
16785
0
    if (node->ChildNodes[0])
16786
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16787
0
    if (node->ChildNodes[1])
16788
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16789
0
    if (node->IsRootNode())
16790
0
    {
16791
0
        ImGuiDockNode* mark_node = node->CentralNode;
16792
0
        while (mark_node)
16793
0
        {
16794
0
            mark_node->HasCentralNodeChild = true;
16795
0
            mark_node = mark_node->ParentNode;
16796
0
        }
16797
0
    }
16798
0
}
16799
16800
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16801
0
{
16802
    // Update visibility flag
16803
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16804
0
    is_visible |= (node->Windows.Size > 0);
16805
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16806
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16807
0
    node->IsVisible = is_visible;
16808
0
}
16809
16810
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16811
0
{
16812
0
    ImGuiContext& g = *GImGui;
16813
0
    IM_ASSERT(node->WantMouseMove == true);
16814
0
    StartMouseMovingWindow(window);
16815
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16816
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16817
0
    node->WantMouseMove = false;
16818
0
}
16819
16820
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16821
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16822
0
{
16823
0
    DockNodeUpdateFlagsAndCollapse(node);
16824
16825
    // - Setup central node pointers
16826
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16827
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16828
0
    ImGuiDockNodeTreeInfo info;
16829
0
    DockNodeFindInfo(node, &info);
16830
0
    node->CentralNode = info.CentralNode;
16831
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16832
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16833
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16834
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16835
16836
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16837
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16838
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16839
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16840
0
    {
16841
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16842
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16843
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16844
0
            {
16845
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16846
0
                break;
16847
0
            }
16848
0
    }
16849
16850
0
    ImGuiDockNode* mark_node = node->CentralNode;
16851
0
    while (mark_node)
16852
0
    {
16853
0
        mark_node->HasCentralNodeChild = true;
16854
0
        mark_node = mark_node->ParentNode;
16855
0
    }
16856
0
}
16857
16858
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16859
0
{
16860
    // Remove ourselves from any previous different host window
16861
    // This can happen if a user mistakenly does (see #4295 for details):
16862
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16863
    //  - N+1: NewFrame()                   // will create floating host window for that node
16864
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16865
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16866
0
        node->HostWindow->DockNodeAsHost = NULL;
16867
16868
0
    host_window->DockNodeAsHost = node;
16869
0
    node->HostWindow = host_window;
16870
0
}
16871
16872
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16873
0
{
16874
0
    ImGuiContext& g = *GImGui;
16875
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16876
0
    node->LastFrameAlive = g.FrameCount;
16877
0
    node->IsBgDrawnThisFrame = false;
16878
16879
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16880
0
    if (node->IsRootNode())
16881
0
        DockNodeUpdateForRootNode(node);
16882
16883
    // Remove tab bar if not needed
16884
0
    if (node->TabBar && node->IsNoTabBar())
16885
0
        DockNodeRemoveTabBar(node);
16886
16887
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16888
0
    bool want_to_hide_host_window = false;
16889
0
    if (node->IsFloatingNode())
16890
0
    {
16891
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16892
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16893
0
                want_to_hide_host_window = true;
16894
0
        if (node->CountNodeWithWindows == 0)
16895
0
            want_to_hide_host_window = true;
16896
0
    }
16897
0
    if (want_to_hide_host_window)
16898
0
    {
16899
0
        if (node->Windows.Size == 1)
16900
0
        {
16901
            // Floating window pos/size is authoritative
16902
0
            ImGuiWindow* single_window = node->Windows[0];
16903
0
            node->Pos = single_window->Pos;
16904
0
            node->Size = single_window->SizeFull;
16905
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16906
16907
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16908
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16909
0
                FocusWindow(single_window);
16910
0
            if (node->HostWindow)
16911
0
            {
16912
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16913
0
                single_window->Viewport = node->HostWindow->Viewport;
16914
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16915
0
                if (node->HostWindow->ViewportOwned)
16916
0
                {
16917
0
                    single_window->Viewport->ID = single_window->ID;
16918
0
                    single_window->Viewport->Window = single_window;
16919
0
                    single_window->ViewportOwned = true;
16920
0
                }
16921
0
            }
16922
0
            node->RefViewportId = single_window->ViewportId;
16923
0
        }
16924
16925
0
        DockNodeHideHostWindow(node);
16926
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16927
0
        node->WantCloseAll = false;
16928
0
        node->WantCloseTabId = 0;
16929
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16930
0
        node->LastFrameActive = g.FrameCount;
16931
16932
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16933
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16934
0
        return;
16935
0
    }
16936
16937
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16938
    // while the expected visible window is resizing itself.
16939
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16940
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16941
    //   N+0: Begin(): window created (with no known size), node is created
16942
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16943
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16944
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16945
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16946
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16947
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16948
0
    {
16949
0
        IM_ASSERT(node->Windows.Size > 0);
16950
0
        ImGuiWindow* ref_window = NULL;
16951
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16952
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16953
0
        if (ref_window == NULL)
16954
0
            ref_window = node->Windows[0];
16955
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16956
0
        {
16957
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16958
0
            return;
16959
0
        }
16960
0
    }
16961
16962
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16963
16964
    // Decide if the node will have a close button and a window menu button
16965
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16966
0
    node->HasCloseButton = false;
16967
0
    for (ImGuiWindow* window : node->Windows)
16968
0
    {
16969
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16970
0
        node->HasCloseButton |= window->HasCloseButton;
16971
0
        window->DockIsActive = (node->Windows.Size > 1);
16972
0
    }
16973
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16974
0
        node->HasCloseButton = false;
16975
16976
    // Bind or create host window
16977
0
    ImGuiWindow* host_window = NULL;
16978
0
    bool beginned_into_host_window = false;
16979
0
    if (node->IsDockSpace())
16980
0
    {
16981
        // [Explicit root dockspace node]
16982
0
        IM_ASSERT(node->HostWindow);
16983
0
        host_window = node->HostWindow;
16984
0
    }
16985
0
    else
16986
0
    {
16987
        // [Automatic root or child nodes]
16988
0
        if (node->IsRootNode() && node->IsVisible)
16989
0
        {
16990
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16991
16992
            // Sync Pos
16993
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16994
0
                SetNextWindowPos(ref_window->Pos);
16995
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16996
0
                SetNextWindowPos(node->Pos);
16997
16998
            // Sync Size
16999
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17000
0
                SetNextWindowSize(ref_window->SizeFull);
17001
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17002
0
                SetNextWindowSize(node->Size);
17003
17004
            // Sync Collapsed
17005
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17006
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17007
17008
            // Sync Viewport
17009
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17010
0
                SetNextWindowViewport(ref_window->ViewportId);
17011
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17012
0
                SetNextWindowViewport(node->RefViewportId);
17013
17014
0
            SetNextWindowClass(&node->WindowClass);
17015
17016
            // Begin into the host window
17017
0
            char window_label[20];
17018
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17019
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17020
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17021
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17022
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17023
17024
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17025
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17026
0
            Begin(window_label, NULL, window_flags);
17027
0
            PopStyleVar();
17028
0
            beginned_into_host_window = true;
17029
17030
0
            host_window = g.CurrentWindow;
17031
0
            DockNodeSetupHostWindow(node, host_window);
17032
0
            host_window->DC.CursorPos = host_window->Pos;
17033
0
            node->Pos = host_window->Pos;
17034
0
            node->Size = host_window->Size;
17035
17036
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17037
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17038
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17039
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17040
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17041
            // after the dock host window, losing their top-most status.
17042
0
            if (node->HostWindow->Appearing)
17043
0
                BringWindowToDisplayFront(node->HostWindow);
17044
17045
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17046
0
        }
17047
0
        else if (node->ParentNode)
17048
0
        {
17049
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17050
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17051
0
        }
17052
0
        if (node->WantMouseMove && node->HostWindow)
17053
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17054
0
    }
17055
0
    node->RefViewportId = 0; // Clear when we have a host window
17056
17057
    // Update focused node (the one whose title bar is highlight) within a node tree
17058
0
    if (node->IsSplitNode())
17059
0
        IM_ASSERT(node->TabBar == NULL);
17060
0
    if (node->IsRootNode())
17061
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17062
0
            while (p_window != NULL && p_window->DockNode != NULL)
17063
0
            {
17064
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17065
0
                if (p_node == node)
17066
0
                {
17067
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17068
0
                    break;
17069
0
                }
17070
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17071
0
            }
17072
17073
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17074
0
    ImGuiDockNode* central_node = node->CentralNode;
17075
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17076
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17077
0
    if (central_node_hole)
17078
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17079
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17080
0
                central_node_hole_register_hit_test_hole = false;
17081
0
    if (central_node_hole_register_hit_test_hole)
17082
0
    {
17083
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17084
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17085
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17086
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17087
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17088
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17089
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17090
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17091
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17092
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17093
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17094
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17095
0
        if (central_node_hole && !hole_rect.IsInverted())
17096
0
        {
17097
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17098
0
            if (host_window->ParentWindow)
17099
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17100
0
        }
17101
0
    }
17102
17103
    // Update position/size, process and draw resizing splitters
17104
0
    if (node->IsRootNode() && host_window)
17105
0
    {
17106
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17107
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17108
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17109
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17110
0
        DockNodeTreeUpdateSplitter(node);
17111
0
        PopStyleColor(3);
17112
0
    }
17113
17114
    // Draw empty node background (currently can only be the Central Node)
17115
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17116
0
    {
17117
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17118
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17119
0
        if (node->LastBgColor != 0)
17120
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17121
0
        node->IsBgDrawnThisFrame = true;
17122
0
    }
17123
17124
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17125
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17126
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17127
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17128
0
    if (render_dockspace_bg && node->IsVisible)
17129
0
    {
17130
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17131
0
        if (central_node_hole)
17132
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17133
0
        else
17134
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17135
0
    }
17136
17137
    // Draw and populate Tab Bar
17138
0
    if (host_window)
17139
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17140
0
    if (host_window && node->Windows.Size > 0)
17141
0
    {
17142
0
        DockNodeUpdateTabBar(node, host_window);
17143
0
    }
17144
0
    else
17145
0
    {
17146
0
        node->WantCloseAll = false;
17147
0
        node->WantCloseTabId = 0;
17148
0
        node->IsFocused = false;
17149
0
    }
17150
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17151
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17152
0
    else if (node->Windows.Size > 0)
17153
0
        node->SelectedTabId = node->Windows[0]->TabId;
17154
17155
    // Draw payload drop target
17156
0
    if (host_window && node->IsVisible)
17157
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17158
0
            BeginDockableDragDropTarget(host_window);
17159
17160
    // We update this after DockNodeUpdateTabBar()
17161
0
    node->LastFrameActive = g.FrameCount;
17162
17163
    // Recurse into children
17164
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17165
0
    if (host_window)
17166
0
    {
17167
0
        if (node->ChildNodes[0])
17168
0
            DockNodeUpdate(node->ChildNodes[0]);
17169
0
        if (node->ChildNodes[1])
17170
0
            DockNodeUpdate(node->ChildNodes[1]);
17171
17172
        // Render outer borders last (after the tab bar)
17173
0
        if (node->IsRootNode())
17174
0
            RenderWindowOuterBorders(host_window);
17175
0
    }
17176
17177
    // End host window
17178
0
    if (beginned_into_host_window) //-V1020
17179
0
        End();
17180
0
}
17181
17182
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17183
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17184
0
{
17185
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17186
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17187
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17188
0
        return d;
17189
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17190
0
}
17191
17192
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17193
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17194
// Custom overrides may want to decorate, group, sort entries.
17195
// Please note those are internal structures: if you copy this expect occasional breakage.
17196
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17197
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17198
0
{
17199
0
    IM_UNUSED(ctx);
17200
0
    if (tab_bar->Tabs.Size == 1)
17201
0
    {
17202
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17203
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17204
0
            node->WantHiddenTabBarToggle = true;
17205
0
    }
17206
0
    else
17207
0
    {
17208
        // Display a selectable list of windows in this docking node
17209
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17210
0
        {
17211
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17212
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17213
0
                continue;
17214
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17215
0
                TabBarQueueFocus(tab_bar, tab);
17216
0
            SameLine();
17217
0
            Text("   ");
17218
0
        }
17219
0
    }
17220
0
}
17221
17222
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17223
0
{
17224
    // Try to position the menu so it is more likely to stays within the same viewport
17225
0
    ImGuiContext& g = *GImGui;
17226
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17227
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17228
0
    else
17229
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17230
0
    if (BeginPopup("#WindowMenu"))
17231
0
    {
17232
0
        node->IsFocused = true;
17233
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17234
0
        EndPopup();
17235
0
    }
17236
0
}
17237
17238
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17239
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17240
0
{
17241
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17242
0
        return false;
17243
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17244
0
        return false;
17245
0
    if (node->TabBar->ID == 0)
17246
0
        return false;
17247
0
    Begin(node->HostWindow->Name);
17248
0
    PushOverrideID(node->ID);
17249
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17250
0
    IM_UNUSED(ret);
17251
0
    IM_ASSERT(ret);
17252
0
    return true;
17253
0
}
17254
17255
void ImGui::DockNodeEndAmendTabBar()
17256
0
{
17257
0
    EndTabBar();
17258
0
    PopID();
17259
0
    End();
17260
0
}
17261
17262
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17263
0
{
17264
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17265
0
    ImGuiContext& g = *GImGui;
17266
0
    if (g.NavWindowingTarget)
17267
0
        return (g.NavWindowingTarget->DockNode == node);
17268
17269
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17270
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17271
0
    {
17272
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17273
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17274
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17275
0
            parent_window = parent_window->ParentWindow->RootWindow;
17276
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17277
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17278
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17279
0
                return true;
17280
0
    }
17281
0
    return false;
17282
0
}
17283
17284
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17285
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17286
0
{
17287
0
    ImGuiContext& g = *GImGui;
17288
0
    ImGuiStyle& style = g.Style;
17289
17290
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17291
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17292
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17293
0
    node->WantCloseAll = false;
17294
0
    node->WantCloseTabId = 0;
17295
17296
    // Decide if we should use a focused title bar color
17297
0
    bool is_focused = false;
17298
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17299
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17300
0
        is_focused = true;
17301
17302
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17303
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17304
0
    {
17305
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17306
0
        node->IsFocused = is_focused;
17307
0
        if (is_focused)
17308
0
            node->LastFrameFocused = g.FrameCount;
17309
0
        if (node->VisibleWindow)
17310
0
        {
17311
            // Notify root of visible window (used to display title in OS task bar)
17312
0
            if (is_focused || root_node->VisibleWindow == NULL)
17313
0
                root_node->VisibleWindow = node->VisibleWindow;
17314
0
            if (node->TabBar)
17315
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17316
0
        }
17317
0
        return;
17318
0
    }
17319
17320
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17321
0
    bool backup_skip_item = host_window->SkipItems;
17322
0
    if (!node->IsDockSpace())
17323
0
    {
17324
0
        host_window->SkipItems = false;
17325
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17326
0
    }
17327
17328
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17329
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17330
    // as docked windows themselves will override the stack with their own root ID.
17331
0
    PushOverrideID(node->ID);
17332
0
    ImGuiTabBar* tab_bar = node->TabBar;
17333
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17334
0
    if (tab_bar == NULL)
17335
0
    {
17336
0
        DockNodeAddTabBar(node);
17337
0
        tab_bar = node->TabBar;
17338
0
    }
17339
17340
0
    ImGuiID focus_tab_id = 0;
17341
0
    node->IsFocused = is_focused;
17342
17343
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17344
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17345
17346
    // In a dock node, the Collapse Button turns into the Window Menu button.
17347
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17348
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17349
0
    {
17350
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17351
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17352
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17353
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17354
0
        is_focused |= node->IsFocused;
17355
0
    }
17356
17357
    // Layout
17358
0
    ImRect title_bar_rect, tab_bar_rect;
17359
0
    ImVec2 window_menu_button_pos;
17360
0
    ImVec2 close_button_pos;
17361
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17362
17363
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17364
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17365
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17366
0
    {
17367
0
        ImGuiWindow* window = node->Windows[window_n];
17368
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17369
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17370
0
    }
17371
17372
    // Title bar
17373
0
    if (is_focused)
17374
0
        node->LastFrameFocused = g.FrameCount;
17375
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17376
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17377
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17378
17379
    // Docking/Collapse button
17380
0
    if (has_window_menu_button)
17381
0
    {
17382
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17383
0
            OpenPopup("#WindowMenu");
17384
0
        if (IsItemActive())
17385
0
            focus_tab_id = tab_bar->SelectedTabId;
17386
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17387
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17388
0
    }
17389
17390
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17391
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17392
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17393
0
    {
17394
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17395
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17396
0
        tabs_unsorted_start = tab_n;
17397
0
    }
17398
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17399
0
    {
17400
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17401
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17402
0
        {
17403
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17404
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17405
0
        }
17406
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17407
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17408
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17409
0
    }
17410
17411
    // Apply NavWindow focus back to the tab bar
17412
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17413
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17414
17415
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17416
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17417
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17418
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17419
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17420
17421
    // Begin tab bar
17422
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17423
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17424
0
    if (!host_window->Collapsed && is_focused)
17425
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17426
0
    tab_bar->ID = GetID("#TabBar");
17427
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17428
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17429
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17430
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17431
17432
    // Backup style colors
17433
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17434
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17435
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17436
17437
    // Submit actual tabs
17438
0
    node->VisibleWindow = NULL;
17439
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17440
0
    {
17441
0
        ImGuiWindow* window = node->Windows[window_n];
17442
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17443
0
            continue;
17444
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17445
0
        {
17446
0
            ImGuiTabItemFlags tab_item_flags = 0;
17447
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17448
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17449
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17450
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17451
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17452
17453
            // Apply stored style overrides for the window
17454
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17455
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17456
17457
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17458
0
            bool tab_open = true;
17459
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17460
0
            if (!tab_open)
17461
0
                node->WantCloseTabId = window->TabId;
17462
0
            if (tab_bar->VisibleTabId == window->TabId)
17463
0
                node->VisibleWindow = window;
17464
17465
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17466
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17467
0
            window->DockTabItemRect = g.LastItemData.Rect;
17468
17469
            // Update navigation ID on menu layer
17470
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17471
0
                host_window->NavLastIds[1] = window->TabId;
17472
0
        }
17473
0
    }
17474
17475
    // Restore style colors
17476
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17477
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17478
17479
    // Notify root of visible window (used to display title in OS task bar)
17480
0
    if (node->VisibleWindow)
17481
0
        if (is_focused || root_node->VisibleWindow == NULL)
17482
0
            root_node->VisibleWindow = node->VisibleWindow;
17483
17484
    // Close button (after VisibleWindow was updated)
17485
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17486
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17487
0
    const bool close_button_is_visible = node->HasCloseButton;
17488
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17489
0
    if (close_button_is_visible)
17490
0
    {
17491
0
        if (!close_button_is_enabled)
17492
0
        {
17493
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17494
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17495
0
        }
17496
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17497
0
        {
17498
0
            node->WantCloseAll = true;
17499
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17500
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17501
0
        }
17502
        //if (IsItemActive())
17503
        //    focus_tab_id = tab_bar->SelectedTabId;
17504
0
        if (!close_button_is_enabled)
17505
0
        {
17506
0
            PopStyleColor();
17507
0
            PopItemFlag();
17508
0
        }
17509
0
    }
17510
17511
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17512
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17513
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17514
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17515
0
    {
17516
        // AllowOverlap mode required for appending into dock node tab bar,
17517
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17518
0
        bool held;
17519
0
        KeepAliveID(title_bar_id);
17520
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17521
0
        if (g.HoveredId == title_bar_id)
17522
0
        {
17523
0
            g.LastItemData.ID = title_bar_id;
17524
0
        }
17525
0
        if (held)
17526
0
        {
17527
0
            if (IsMouseClicked(0))
17528
0
                focus_tab_id = tab_bar->SelectedTabId;
17529
17530
            // Forward moving request to selected window
17531
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17532
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17533
0
        }
17534
0
    }
17535
17536
    // Forward focus from host node to selected window
17537
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17538
    //    focus_tab_id = tab_bar->SelectedTabId;
17539
17540
    // When clicked on a tab we requested focus to the docked child
17541
    // This overrides the value set by "forward focus from host node to selected window".
17542
0
    if (tab_bar->NextSelectedTabId)
17543
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17544
17545
    // Apply navigation focus
17546
0
    if (focus_tab_id != 0)
17547
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17548
0
            if (tab->Window)
17549
0
            {
17550
0
                FocusWindow(tab->Window);
17551
0
                NavInitWindow(tab->Window, false);
17552
0
            }
17553
17554
0
    EndTabBar();
17555
0
    PopID();
17556
17557
    // Restore SkipItems flag
17558
0
    if (!node->IsDockSpace())
17559
0
    {
17560
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17561
0
        host_window->SkipItems = backup_skip_item;
17562
0
    }
17563
0
}
17564
17565
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17566
0
{
17567
0
    IM_ASSERT(node->TabBar == NULL);
17568
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17569
0
}
17570
17571
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17572
0
{
17573
0
    if (node->TabBar == NULL)
17574
0
        return;
17575
0
    IM_DELETE(node->TabBar);
17576
0
    node->TabBar = NULL;
17577
0
}
17578
17579
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17580
0
{
17581
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17582
0
        return false;
17583
17584
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17585
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17586
0
    if (host_class->ClassId != payload_class->ClassId)
17587
0
    {
17588
0
        bool pass = false;
17589
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17590
0
            pass = true;
17591
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17592
0
            pass = true;
17593
0
        if (!pass)
17594
0
            return false;
17595
0
    }
17596
17597
    // Prevent docking any window created above a popup
17598
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17599
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17600
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17601
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17602
0
    ImGuiContext& g = *GImGui;
17603
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17604
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17605
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17606
0
                return false;
17607
17608
0
    return true;
17609
0
}
17610
17611
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17612
0
{
17613
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17614
0
        return true;
17615
17616
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17617
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17618
0
    {
17619
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17620
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17621
0
            return true;
17622
0
    }
17623
0
    return false;
17624
0
}
17625
17626
// window menu button == collapse button when not in a dock node.
17627
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17628
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17629
0
{
17630
0
    ImGuiContext& g = *GImGui;
17631
0
    ImGuiStyle& style = g.Style;
17632
17633
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17634
0
    if (out_title_rect) { *out_title_rect = r; }
17635
17636
0
    r.Min.x += style.WindowBorderSize;
17637
0
    r.Max.x -= style.WindowBorderSize;
17638
17639
0
    float button_sz = g.FontSize;
17640
0
    r.Min.x += style.FramePadding.x;
17641
0
    r.Max.x -= style.FramePadding.x;
17642
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17643
0
    if (node->HasCloseButton)
17644
0
    {
17645
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17646
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17647
0
    }
17648
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17649
0
    {
17650
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17651
0
    }
17652
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17653
0
    {
17654
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17655
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17656
0
    }
17657
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17658
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17659
0
}
17660
17661
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17662
0
{
17663
0
    ImGuiContext& g = *GImGui;
17664
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17665
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17666
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17667
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17668
17669
    // Distribute size on given axis (with a desired size or equally)
17670
0
    const float w_avail = size_old[axis] - dock_spacing;
17671
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17672
0
    {
17673
0
        size_new[axis] = size_new_desired[axis];
17674
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17675
0
    }
17676
0
    else
17677
0
    {
17678
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17679
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17680
0
    }
17681
17682
    // Position each node
17683
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17684
0
    {
17685
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17686
0
    }
17687
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17688
0
    {
17689
0
        pos_new[axis] = pos_old[axis];
17690
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17691
0
    }
17692
0
}
17693
17694
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17695
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17696
0
{
17697
0
    ImGuiContext& g = *GImGui;
17698
17699
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17700
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17701
0
    float hs_w; // Half-size, longer axis
17702
0
    float hs_h; // Half-size, smaller axis
17703
0
    ImVec2 off; // Distance from edge or center
17704
0
    if (outer_docking)
17705
0
    {
17706
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17707
        //hs_h = ImTrunc(hs_w * 0.15f);
17708
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17709
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17710
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17711
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17712
0
    }
17713
0
    else
17714
0
    {
17715
0
        hs_w = ImTrunc(hs_for_central_nodes);
17716
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17717
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17718
0
    }
17719
17720
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17721
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17722
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17723
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17724
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17725
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17726
17727
0
    if (test_mouse_pos == NULL)
17728
0
        return false;
17729
17730
0
    ImRect hit_r = out_r;
17731
0
    if (!outer_docking)
17732
0
    {
17733
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17734
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17735
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17736
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17737
0
        float r_threshold_center = hs_w * 1.4f;
17738
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17739
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17740
0
            return (dir == ImGuiDir_None);
17741
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17742
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17743
0
    }
17744
0
    return hit_r.Contains(*test_mouse_pos);
17745
0
}
17746
17747
// host_node may be NULL if the window doesn't have a DockNode already.
17748
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17749
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17750
0
{
17751
0
    ImGuiContext& g = *GImGui;
17752
17753
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17754
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17755
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17756
0
    if (payload_node == NULL)
17757
0
        payload_node = payload_window->DockNodeAsHost;
17758
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17759
0
    if (ref_node_for_rect)
17760
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17761
17762
    // Filter, figure out where we are allowed to dock
17763
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17764
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17765
0
    data->IsCenterAvailable = true;
17766
0
    if (is_outer_docking)
17767
0
        data->IsCenterAvailable = false;
17768
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17769
0
        data->IsCenterAvailable = false;
17770
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17771
0
        data->IsCenterAvailable = false;
17772
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17773
0
        data->IsCenterAvailable = false;
17774
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17775
0
        data->IsCenterAvailable = false;
17776
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17777
0
        data->IsCenterAvailable = false;
17778
17779
0
    data->IsSidesAvailable = true;
17780
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17781
0
        data->IsSidesAvailable = false;
17782
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17783
0
        data->IsSidesAvailable = false;
17784
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17785
0
        data->IsSidesAvailable = false;
17786
17787
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17788
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17789
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17790
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17791
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17792
17793
    // Calculate drop shapes geometry for allowed splitting directions
17794
0
    IM_ASSERT(ImGuiDir_None == -1);
17795
0
    data->SplitNode = host_node;
17796
0
    data->SplitDir = ImGuiDir_None;
17797
0
    data->IsSplitDirExplicit = false;
17798
0
    if (!host_window->Collapsed)
17799
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17800
0
        {
17801
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17802
0
                continue;
17803
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17804
0
                continue;
17805
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17806
0
            {
17807
0
                data->SplitDir = (ImGuiDir)dir;
17808
0
                data->IsSplitDirExplicit = true;
17809
0
            }
17810
0
        }
17811
17812
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17813
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17814
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17815
0
        data->IsDropAllowed = false;
17816
17817
    // Calculate split area
17818
0
    data->SplitRatio = 0.0f;
17819
0
    if (data->SplitDir != ImGuiDir_None)
17820
0
    {
17821
0
        ImGuiDir split_dir = data->SplitDir;
17822
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17823
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17824
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17825
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17826
17827
        // Calculate split ratio so we can pass it down the docking request
17828
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17829
0
        data->FutureNode.Pos = pos_new;
17830
0
        data->FutureNode.Size = size_new;
17831
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17832
0
    }
17833
0
}
17834
17835
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17836
0
{
17837
0
    ImGuiContext& g = *GImGui;
17838
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17839
17840
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17841
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17842
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17843
17844
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17845
0
    int overlay_draw_lists_count = 0;
17846
0
    ImDrawList* overlay_draw_lists[2];
17847
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17848
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17849
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17850
17851
    // Draw main preview rectangle
17852
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17853
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17854
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17855
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17856
17857
    // Display area preview
17858
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17859
0
    if (data->IsDropAllowed)
17860
0
    {
17861
0
        ImRect overlay_rect = data->FutureNode.Rect();
17862
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17863
0
            overlay_rect.Min.y += GetFrameHeight();
17864
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17865
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17866
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17867
0
    }
17868
17869
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17870
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17871
0
    {
17872
        // Compute target tab bar geometry so we can locate our preview tabs
17873
0
        ImRect tab_bar_rect;
17874
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17875
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17876
0
        if (host_node && host_node->TabBar)
17877
0
        {
17878
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17879
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17880
0
            else
17881
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17882
0
        }
17883
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17884
0
        {
17885
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17886
0
        }
17887
17888
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17889
0
        if (root_payload->DockNodeAsHost)
17890
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17891
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17892
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17893
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17894
0
        {
17895
            // DockNode's TabBar may have non-window Tabs manually appended by user
17896
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17897
0
            if (tab_bar_with_payload && payload_window == NULL)
17898
0
                continue;
17899
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17900
0
                continue;
17901
17902
            // Calculate the tab bounding box for each payload window
17903
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17904
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17905
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17906
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17907
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17908
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17909
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17910
0
            {
17911
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17912
0
                if (!tab_bar_rect.Contains(tab_bb))
17913
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17914
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17915
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17916
0
                if (!tab_bar_rect.Contains(tab_bb))
17917
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17918
0
            }
17919
0
            PopStyleColor();
17920
0
        }
17921
0
    }
17922
17923
    // Display drop boxes
17924
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17925
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17926
0
    {
17927
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17928
0
        {
17929
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17930
0
            ImRect draw_r_in = draw_r;
17931
0
            draw_r_in.Expand(-2.0f);
17932
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17933
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17934
0
            {
17935
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17936
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17937
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17938
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17939
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17940
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17941
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17942
0
            }
17943
0
        }
17944
17945
        // Stop after ImGuiDir_None
17946
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17947
0
            return;
17948
0
    }
17949
0
}
17950
17951
//-----------------------------------------------------------------------------
17952
// Docking: ImGuiDockNode Tree manipulation functions
17953
//-----------------------------------------------------------------------------
17954
// - DockNodeTreeSplit()
17955
// - DockNodeTreeMerge()
17956
// - DockNodeTreeUpdatePosSize()
17957
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17958
// - DockNodeTreeUpdateSplitter()
17959
// - DockNodeTreeFindFallbackLeafNode()
17960
// - DockNodeTreeFindNodeByPos()
17961
//-----------------------------------------------------------------------------
17962
17963
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17964
0
{
17965
0
    ImGuiContext& g = *GImGui;
17966
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17967
17968
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17969
0
    child_0->ParentNode = parent_node;
17970
17971
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17972
0
    child_1->ParentNode = parent_node;
17973
17974
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17975
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17976
0
    parent_node->ChildNodes[0] = child_0;
17977
0
    parent_node->ChildNodes[1] = child_1;
17978
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17979
0
    parent_node->SplitAxis = split_axis;
17980
0
    parent_node->VisibleWindow = NULL;
17981
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17982
17983
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17984
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17985
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17986
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17987
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17988
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17989
17990
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17991
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17992
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17993
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17994
17995
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17996
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17997
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17998
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17999
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18000
0
    child_0->UpdateMergedFlags();
18001
0
    child_1->UpdateMergedFlags();
18002
0
    parent_node->UpdateMergedFlags();
18003
0
    if (child_inheritor->IsCentralNode())
18004
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18005
0
}
18006
18007
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18008
0
{
18009
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18010
0
    ImGuiContext& g = *GImGui;
18011
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18012
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18013
0
    IM_ASSERT(child_0 || child_1);
18014
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18015
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18016
0
    {
18017
0
        IM_ASSERT(parent_node->TabBar == NULL);
18018
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18019
0
    }
18020
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18021
18022
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18023
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18024
0
    if (child_0)
18025
0
    {
18026
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18027
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18028
0
    }
18029
0
    if (child_1)
18030
0
    {
18031
0
        DockNodeMoveWindows(parent_node, child_1);
18032
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18033
0
    }
18034
0
    DockNodeApplyPosSizeToWindows(parent_node);
18035
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18036
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18037
0
    parent_node->SizeRef = backup_last_explicit_size;
18038
18039
    // Flags transfer
18040
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18041
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18042
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18043
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18044
0
    parent_node->UpdateMergedFlags();
18045
18046
0
    if (child_0)
18047
0
    {
18048
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18049
0
        IM_DELETE(child_0);
18050
0
    }
18051
0
    if (child_1)
18052
0
    {
18053
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18054
0
        IM_DELETE(child_1);
18055
0
    }
18056
0
}
18057
18058
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18059
// (Depth-first, Pre-Order)
18060
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18061
0
{
18062
    // During the regular dock node update we write to all nodes.
18063
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18064
0
    ImGuiContext& g = *GImGui;
18065
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18066
0
    if (write_to_node)
18067
0
    {
18068
0
        node->Pos = pos;
18069
0
        node->Size = size;
18070
0
    }
18071
18072
0
    if (node->IsLeafNode())
18073
0
        return;
18074
18075
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18076
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18077
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18078
0
    ImVec2 child_0_size = size, child_1_size = size;
18079
18080
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18081
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18082
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18083
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18084
18085
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18086
0
    {
18087
0
        const float spacing = g.Style.DockingSeparatorSize;
18088
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18089
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18090
18091
        // Size allocation policy
18092
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18093
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18094
18095
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18096
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18097
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18098
18099
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18100
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18101
0
        {
18102
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18103
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18104
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18105
0
        }
18106
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18107
0
        {
18108
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18109
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18110
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18111
0
        }
18112
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18113
0
        {
18114
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18115
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18116
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18117
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18118
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18119
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18120
0
        }
18121
18122
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18123
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18124
0
        {
18125
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18126
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18127
0
        }
18128
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18129
0
        {
18130
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18131
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18132
0
        }
18133
0
        else
18134
0
        {
18135
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18136
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18137
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18138
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18139
0
        }
18140
18141
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18142
0
    }
18143
18144
0
    if (only_write_to_single_node == NULL)
18145
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18146
18147
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18148
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18149
0
    if (child_0_recurse)
18150
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18151
0
    if (child_1_recurse)
18152
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18153
0
}
18154
18155
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18156
0
{
18157
0
    if (node->IsLeafNode())
18158
0
    {
18159
0
        touching_nodes->push_back(node);
18160
0
        return;
18161
0
    }
18162
0
    if (node->ChildNodes[0]->IsVisible)
18163
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18164
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18165
0
    if (node->ChildNodes[1]->IsVisible)
18166
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18167
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18168
0
}
18169
18170
// (Depth-First, Pre-Order)
18171
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18172
0
{
18173
0
    if (node->IsLeafNode())
18174
0
        return;
18175
18176
0
    ImGuiContext& g = *GImGui;
18177
18178
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18179
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18180
0
    if (child_0->IsVisible && child_1->IsVisible)
18181
0
    {
18182
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18183
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18184
0
        IM_ASSERT(axis != ImGuiAxis_None);
18185
0
        ImRect bb;
18186
0
        bb.Min = child_0->Pos;
18187
0
        bb.Max = child_1->Pos;
18188
0
        bb.Min[axis] += child_0->Size[axis];
18189
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18190
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18191
18192
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18193
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18194
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18195
0
        {
18196
0
            ImGuiWindow* window = g.CurrentWindow;
18197
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18198
0
        }
18199
0
        else
18200
0
        {
18201
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18202
            //bb.Max[axis] -= 1;
18203
0
            PushID(node->ID);
18204
18205
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18206
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18207
0
            float min_size = g.Style.WindowMinSize[axis];
18208
0
            float resize_limits[2];
18209
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18210
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18211
18212
0
            ImGuiID splitter_id = GetID("##Splitter");
18213
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18214
0
            {
18215
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18216
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18217
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18218
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18219
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18220
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18221
18222
                // [DEBUG] Render touching nodes & limits
18223
                /*
18224
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18225
                for (int n = 0; n < 2; n++)
18226
                {
18227
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18228
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18229
                    if (axis == ImGuiAxis_X)
18230
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18231
                    else
18232
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18233
                }
18234
                */
18235
0
            }
18236
18237
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18238
0
            float cur_size_0 = child_0->Size[axis];
18239
0
            float cur_size_1 = child_1->Size[axis];
18240
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18241
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18242
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18243
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18244
0
            {
18245
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18246
0
                {
18247
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18248
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18249
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18250
18251
                    // Lock the size of every node that is a sibling of the node we are touching
18252
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18253
0
                    for (int side_n = 0; side_n < 2; side_n++)
18254
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18255
0
                        {
18256
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18257
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18258
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18259
0
                            while (touching_node->ParentNode != node)
18260
0
                            {
18261
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18262
0
                                {
18263
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18264
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18265
0
                                    node_to_preserve->WantLockSizeOnce = true;
18266
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18267
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18268
0
                                }
18269
0
                                touching_node = touching_node->ParentNode;
18270
0
                            }
18271
0
                        }
18272
18273
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18274
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18275
0
                    MarkIniSettingsDirty();
18276
0
                }
18277
0
            }
18278
0
            PopID();
18279
0
        }
18280
0
    }
18281
18282
0
    if (child_0->IsVisible)
18283
0
        DockNodeTreeUpdateSplitter(child_0);
18284
0
    if (child_1->IsVisible)
18285
0
        DockNodeTreeUpdateSplitter(child_1);
18286
0
}
18287
18288
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18289
0
{
18290
0
    if (node->IsLeafNode())
18291
0
        return node;
18292
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18293
0
        return leaf_node;
18294
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18295
0
        return leaf_node;
18296
0
    return NULL;
18297
0
}
18298
18299
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18300
0
{
18301
0
    if (!node->IsVisible)
18302
0
        return NULL;
18303
18304
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18305
0
    ImRect r(node->Pos, node->Pos + node->Size);
18306
0
    r.Expand(dock_spacing * 0.5f);
18307
0
    bool inside = r.Contains(pos);
18308
0
    if (!inside)
18309
0
        return NULL;
18310
18311
0
    if (node->IsLeafNode())
18312
0
        return node;
18313
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18314
0
        return hovered_node;
18315
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18316
0
        return hovered_node;
18317
18318
    // This means we are hovering over the splitter/spacing of a parent node
18319
0
    return node;
18320
0
}
18321
18322
//-----------------------------------------------------------------------------
18323
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18324
//-----------------------------------------------------------------------------
18325
// - SetWindowDock() [Internal]
18326
// - DockSpace()
18327
// - DockSpaceOverViewport()
18328
//-----------------------------------------------------------------------------
18329
18330
// [Internal] Called via SetNextWindowDockID()
18331
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18332
0
{
18333
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18334
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18335
0
        return;
18336
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18337
18338
0
    if (window->DockId == dock_id)
18339
0
        return;
18340
18341
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18342
0
    ImGuiContext& g = *GImGui;
18343
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18344
0
        if (new_node->IsSplitNode())
18345
0
        {
18346
            // Policy: Find central node or latest focused node. We first move back to our root node.
18347
0
            new_node = DockNodeGetRootNode(new_node);
18348
0
            if (new_node->CentralNode)
18349
0
            {
18350
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18351
0
                dock_id = new_node->CentralNode->ID;
18352
0
            }
18353
0
            else
18354
0
            {
18355
0
                dock_id = new_node->LastFocusedNodeId;
18356
0
            }
18357
0
        }
18358
18359
0
    if (window->DockId == dock_id)
18360
0
        return;
18361
18362
0
    if (window->DockNode)
18363
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18364
0
    window->DockId = dock_id;
18365
0
}
18366
18367
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18368
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18369
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18370
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18371
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18372
0
{
18373
0
    ImGuiContext& g = *GImGui;
18374
0
    ImGuiWindow* window = GetCurrentWindowRead();
18375
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18376
0
        return 0;
18377
18378
    // Early out if parent window is hidden/collapsed
18379
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18380
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18381
0
    if (window->SkipItems)
18382
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18383
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18384
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18385
18386
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18387
0
    IM_ASSERT(id != 0);
18388
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18389
0
    if (!node)
18390
0
    {
18391
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18392
0
        node = DockContextAddNode(&g, id);
18393
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18394
0
    }
18395
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18396
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18397
0
    node->SharedFlags = flags;
18398
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18399
18400
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18401
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18402
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18403
0
    {
18404
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18405
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18406
0
        return id;
18407
0
    }
18408
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18409
18410
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18411
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18412
0
    {
18413
0
        node->LastFrameAlive = g.FrameCount;
18414
0
        return id;
18415
0
    }
18416
18417
0
    const ImVec2 content_avail = GetContentRegionAvail();
18418
0
    ImVec2 size = ImTrunc(size_arg);
18419
0
    if (size.x <= 0.0f)
18420
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18421
0
    if (size.y <= 0.0f)
18422
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18423
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18424
18425
0
    node->Pos = window->DC.CursorPos;
18426
0
    node->Size = node->SizeRef = size;
18427
0
    SetNextWindowPos(node->Pos);
18428
0
    SetNextWindowSize(node->Size);
18429
0
    g.NextWindowData.PosUndock = false;
18430
18431
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18432
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18433
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18434
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18435
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18436
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18437
18438
0
    char title[256];
18439
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18440
18441
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18442
0
    Begin(title, NULL, window_flags);
18443
0
    PopStyleVar();
18444
18445
0
    ImGuiWindow* host_window = g.CurrentWindow;
18446
0
    DockNodeSetupHostWindow(node, host_window);
18447
0
    host_window->ChildId = window->GetID(title);
18448
0
    node->OnlyNodeWithWindows = NULL;
18449
18450
0
    IM_ASSERT(node->IsRootNode());
18451
18452
    // We need to handle the rare case were a central node is missing.
18453
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18454
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18455
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18456
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18457
    // as it doesn't make sense for an empty dockspace to not have this property.
18458
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18459
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18460
18461
    // Update the node
18462
0
    DockNodeUpdate(node);
18463
18464
0
    End();
18465
18466
0
    ImRect bb(node->Pos, node->Pos + size);
18467
0
    ItemSize(size);
18468
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18469
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18470
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18471
18472
0
    return id;
18473
0
}
18474
18475
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18476
// The limitation with this call is that your window won't have a menu bar.
18477
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18478
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18479
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18480
0
{
18481
0
    if (viewport == NULL)
18482
0
        viewport = GetMainViewport();
18483
18484
0
    SetNextWindowPos(viewport->WorkPos);
18485
0
    SetNextWindowSize(viewport->WorkSize);
18486
0
    SetNextWindowViewport(viewport->ID);
18487
18488
0
    ImGuiWindowFlags host_window_flags = 0;
18489
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18490
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18491
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18492
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18493
18494
0
    char label[32];
18495
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18496
18497
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18498
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18499
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18500
0
    Begin(label, NULL, host_window_flags);
18501
0
    PopStyleVar(3);
18502
18503
0
    ImGuiID dockspace_id = GetID("DockSpace");
18504
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18505
0
    End();
18506
18507
0
    return dockspace_id;
18508
0
}
18509
18510
//-----------------------------------------------------------------------------
18511
// Docking: Builder Functions
18512
//-----------------------------------------------------------------------------
18513
// Very early end-user API to manipulate dock nodes.
18514
// Only available in imgui_internal.h. Expect this API to change/break!
18515
// It is expected that those functions are all called _before_ the dockspace node submission.
18516
//-----------------------------------------------------------------------------
18517
// - DockBuilderDockWindow()
18518
// - DockBuilderGetNode()
18519
// - DockBuilderSetNodePos()
18520
// - DockBuilderSetNodeSize()
18521
// - DockBuilderAddNode()
18522
// - DockBuilderRemoveNode()
18523
// - DockBuilderRemoveNodeChildNodes()
18524
// - DockBuilderRemoveNodeDockedWindows()
18525
// - DockBuilderSplitNode()
18526
// - DockBuilderCopyNodeRec()
18527
// - DockBuilderCopyNode()
18528
// - DockBuilderCopyWindowSettings()
18529
// - DockBuilderCopyDockSpace()
18530
// - DockBuilderFinish()
18531
//-----------------------------------------------------------------------------
18532
18533
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18534
0
{
18535
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18536
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18537
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18538
0
    ImGuiID window_id = ImHashStr(window_name);
18539
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18540
0
    {
18541
        // Apply to created window
18542
0
        ImGuiID prev_node_id = window->DockId;
18543
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18544
0
        if (window->DockId != prev_node_id)
18545
0
            window->DockOrder = -1;
18546
0
    }
18547
0
    else
18548
0
    {
18549
        // Apply to settings
18550
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18551
0
        if (settings == NULL)
18552
0
            settings = CreateNewWindowSettings(window_name);
18553
0
        if (settings->DockId != node_id)
18554
0
            settings->DockOrder = -1;
18555
0
        settings->DockId = node_id;
18556
0
    }
18557
0
}
18558
18559
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18560
0
{
18561
0
    ImGuiContext& g = *GImGui;
18562
0
    return DockContextFindNodeByID(&g, node_id);
18563
0
}
18564
18565
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18566
0
{
18567
0
    ImGuiContext& g = *GImGui;
18568
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18569
0
    if (node == NULL)
18570
0
        return;
18571
0
    node->Pos = pos;
18572
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18573
0
}
18574
18575
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18576
0
{
18577
0
    ImGuiContext& g = *GImGui;
18578
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18579
0
    if (node == NULL)
18580
0
        return;
18581
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18582
0
    node->Size = node->SizeRef = size;
18583
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18584
0
}
18585
18586
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18587
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18588
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18589
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18590
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18591
// - Use (id == 0) to let the system allocate a node identifier.
18592
// - Existing node with a same id will be removed.
18593
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18594
0
{
18595
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18596
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18597
18598
0
    if (node_id != 0)
18599
0
        DockBuilderRemoveNode(node_id);
18600
18601
0
    ImGuiDockNode* node = NULL;
18602
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18603
0
    {
18604
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18605
0
        node = DockContextFindNodeByID(&g, node_id);
18606
0
    }
18607
0
    else
18608
0
    {
18609
0
        node = DockContextAddNode(&g, node_id);
18610
0
        node->SetLocalFlags(flags);
18611
0
    }
18612
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18613
0
    return node->ID;
18614
0
}
18615
18616
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18617
0
{
18618
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18619
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18620
18621
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18622
0
    if (node == NULL)
18623
0
        return;
18624
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18625
0
    DockBuilderRemoveNodeChildNodes(node_id);
18626
    // Node may have moved or deleted if e.g. any merge happened
18627
0
    node = DockContextFindNodeByID(&g, node_id);
18628
0
    if (node == NULL)
18629
0
        return;
18630
0
    if (node->IsCentralNode() && node->ParentNode)
18631
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18632
0
    DockContextRemoveNode(&g, node, true);
18633
0
}
18634
18635
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18636
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18637
0
{
18638
0
    ImGuiContext& g = *GImGui;
18639
0
    ImGuiDockContext* dc = &g.DockContext;
18640
18641
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
18642
0
    if (root_id && root_node == NULL)
18643
0
        return;
18644
0
    bool has_central_node = false;
18645
18646
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18647
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18648
18649
    // Process active windows
18650
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18651
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18652
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18653
0
        {
18654
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18655
0
            if (want_removal)
18656
0
            {
18657
0
                if (node->IsCentralNode())
18658
0
                    has_central_node = true;
18659
0
                if (root_id != 0)
18660
0
                    DockContextQueueNotifyRemovedNode(&g, node);
18661
0
                if (root_node)
18662
0
                {
18663
0
                    DockNodeMoveWindows(root_node, node);
18664
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18665
0
                }
18666
0
                nodes_to_remove.push_back(node);
18667
0
            }
18668
0
        }
18669
18670
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18671
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18672
0
    if (root_node)
18673
0
    {
18674
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18675
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18676
0
    }
18677
18678
    // Apply to settings
18679
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18680
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18681
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18682
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18683
0
                {
18684
0
                    settings->DockId = root_id;
18685
0
                    break;
18686
0
                }
18687
18688
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18689
0
    if (nodes_to_remove.Size > 1)
18690
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18691
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18692
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
18693
18694
0
    if (root_id == 0)
18695
0
    {
18696
0
        dc->Nodes.Clear();
18697
0
        dc->Requests.clear();
18698
0
    }
18699
0
    else if (has_central_node)
18700
0
    {
18701
0
        root_node->CentralNode = root_node;
18702
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18703
0
    }
18704
0
}
18705
18706
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18707
0
{
18708
    // Clear references in settings
18709
0
    ImGuiContext& g = *GImGui;
18710
0
    if (clear_settings_refs)
18711
0
    {
18712
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18713
0
        {
18714
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18715
0
            if (!want_removal && settings->DockId != 0)
18716
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
18717
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18718
0
                        want_removal = true;
18719
0
            if (want_removal)
18720
0
                settings->DockId = 0;
18721
0
        }
18722
0
    }
18723
18724
    // Clear references in windows
18725
0
    for (int n = 0; n < g.Windows.Size; n++)
18726
0
    {
18727
0
        ImGuiWindow* window = g.Windows[n];
18728
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18729
0
        if (want_removal)
18730
0
        {
18731
0
            const ImGuiID backup_dock_id = window->DockId;
18732
0
            IM_UNUSED(backup_dock_id);
18733
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
18734
0
            if (!clear_settings_refs)
18735
0
                IM_ASSERT(window->DockId == backup_dock_id);
18736
0
        }
18737
0
    }
18738
0
}
18739
18740
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18741
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18742
// FIXME-DOCK: We are not exposing nor using split_outer.
18743
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18744
0
{
18745
0
    ImGuiContext& g = *GImGui;
18746
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18747
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18748
18749
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18750
0
    if (node == NULL)
18751
0
    {
18752
0
        IM_ASSERT(node != NULL);
18753
0
        return 0;
18754
0
    }
18755
18756
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18757
18758
0
    ImGuiDockRequest req;
18759
0
    req.Type = ImGuiDockRequestType_Split;
18760
0
    req.DockTargetWindow = NULL;
18761
0
    req.DockTargetNode = node;
18762
0
    req.DockPayload = NULL;
18763
0
    req.DockSplitDir = split_dir;
18764
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18765
0
    req.DockSplitOuter = false;
18766
0
    DockContextProcessDock(&g, &req);
18767
18768
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18769
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18770
0
    if (out_id_at_dir)
18771
0
        *out_id_at_dir = id_at_dir;
18772
0
    if (out_id_at_opposite_dir)
18773
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18774
0
    return id_at_dir;
18775
0
}
18776
18777
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18778
0
{
18779
0
    ImGuiContext& g = *GImGui;
18780
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18781
0
    dst_node->SharedFlags = src_node->SharedFlags;
18782
0
    dst_node->LocalFlags = src_node->LocalFlags;
18783
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18784
0
    dst_node->Pos = src_node->Pos;
18785
0
    dst_node->Size = src_node->Size;
18786
0
    dst_node->SizeRef = src_node->SizeRef;
18787
0
    dst_node->SplitAxis = src_node->SplitAxis;
18788
0
    dst_node->UpdateMergedFlags();
18789
18790
0
    out_node_remap_pairs->push_back(src_node->ID);
18791
0
    out_node_remap_pairs->push_back(dst_node->ID);
18792
18793
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18794
0
        if (src_node->ChildNodes[child_n])
18795
0
        {
18796
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18797
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18798
0
        }
18799
18800
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18801
0
    return dst_node;
18802
0
}
18803
18804
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18805
0
{
18806
0
    ImGuiContext& g = *GImGui;
18807
0
    IM_ASSERT(src_node_id != 0);
18808
0
    IM_ASSERT(dst_node_id != 0);
18809
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18810
18811
0
    DockBuilderRemoveNode(dst_node_id);
18812
18813
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
18814
0
    IM_ASSERT(src_node != NULL);
18815
18816
0
    out_node_remap_pairs->clear();
18817
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18818
18819
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18820
0
}
18821
18822
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18823
0
{
18824
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18825
0
    if (src_window == NULL)
18826
0
        return;
18827
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18828
0
    {
18829
0
        dst_window->Pos = src_window->Pos;
18830
0
        dst_window->Size = src_window->Size;
18831
0
        dst_window->SizeFull = src_window->SizeFull;
18832
0
        dst_window->Collapsed = src_window->Collapsed;
18833
0
    }
18834
0
    else
18835
0
    {
18836
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18837
0
        if (!dst_settings)
18838
0
            dst_settings = CreateNewWindowSettings(dst_name);
18839
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18840
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18841
0
        {
18842
0
            dst_settings->ViewportPos = window_pos_2ih;
18843
0
            dst_settings->ViewportId = src_window->ViewportId;
18844
0
            dst_settings->Pos = ImVec2ih(0, 0);
18845
0
        }
18846
0
        else
18847
0
        {
18848
0
            dst_settings->Pos = window_pos_2ih;
18849
0
        }
18850
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18851
0
        dst_settings->Collapsed = src_window->Collapsed;
18852
0
    }
18853
0
}
18854
18855
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18856
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18857
0
{
18858
0
    ImGuiContext& g = *GImGui;
18859
0
    IM_ASSERT(src_dockspace_id != 0);
18860
0
    IM_ASSERT(dst_dockspace_id != 0);
18861
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18862
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18863
18864
    // Duplicate entire dock
18865
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18866
    // whereas we could attempt to at least keep them together in a new, same floating node.
18867
0
    ImVector<ImGuiID> node_remap_pairs;
18868
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18869
18870
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18871
    // (The windows associated to src_dockspace_id are staying in place)
18872
0
    ImVector<ImGuiID> src_windows;
18873
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18874
0
    {
18875
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18876
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18877
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18878
0
        src_windows.push_back(src_window_id);
18879
18880
        // Search in the remapping tables
18881
0
        ImGuiID src_dock_id = 0;
18882
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18883
0
            src_dock_id = src_window->DockId;
18884
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18885
0
            src_dock_id = src_window_settings->DockId;
18886
0
        ImGuiID dst_dock_id = 0;
18887
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18888
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18889
0
            {
18890
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18891
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18892
0
                break;
18893
0
            }
18894
18895
0
        if (dst_dock_id != 0)
18896
0
        {
18897
            // Docked windows gets redocked into the new node hierarchy.
18898
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18899
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18900
0
        }
18901
0
        else
18902
0
        {
18903
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18904
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18905
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18906
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18907
0
        }
18908
0
    }
18909
18910
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18911
    // Find those windows and move to them to the cloned dock node. This may be optional?
18912
    // Dock those are a second step as undocking would invalidate source dock nodes.
18913
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18914
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18915
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18916
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18917
0
        {
18918
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18919
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18920
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18921
0
            {
18922
0
                ImGuiWindow* window = node->Windows[window_n];
18923
0
                if (src_windows.contains(window->ID))
18924
0
                    continue;
18925
18926
                // Docked windows gets redocked into the new node hierarchy.
18927
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18928
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18929
0
            }
18930
0
        }
18931
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18932
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18933
0
}
18934
18935
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18936
void ImGui::DockBuilderFinish(ImGuiID root_id)
18937
0
{
18938
0
    ImGuiContext& g = *GImGui;
18939
    //DockContextRebuild(&g);
18940
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
18941
0
}
18942
18943
//-----------------------------------------------------------------------------
18944
// Docking: Begin/End Support Functions (called from Begin/End)
18945
//-----------------------------------------------------------------------------
18946
// - GetWindowAlwaysWantOwnTabBar()
18947
// - DockContextBindNodeToWindow()
18948
// - BeginDocked()
18949
// - BeginDockableDragDropSource()
18950
// - BeginDockableDragDropTarget()
18951
//-----------------------------------------------------------------------------
18952
18953
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18954
44.8k
{
18955
44.8k
    ImGuiContext& g = *GImGui;
18956
44.8k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18957
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18958
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18959
0
                return true;
18960
44.8k
    return false;
18961
44.8k
}
18962
18963
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18964
0
{
18965
0
    ImGuiContext& g = *ctx;
18966
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18967
0
    IM_ASSERT(window->DockNode == NULL);
18968
18969
    // We should not be docking into a split node (SetWindowDock should avoid this)
18970
0
    if (node && node->IsSplitNode())
18971
0
    {
18972
0
        DockContextProcessUndockWindow(ctx, window);
18973
0
        return NULL;
18974
0
    }
18975
18976
    // Create node
18977
0
    if (node == NULL)
18978
0
    {
18979
0
        node = DockContextAddNode(ctx, window->DockId);
18980
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18981
0
        node->LastFrameAlive = g.FrameCount;
18982
0
    }
18983
18984
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18985
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18986
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18987
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18988
0
    if (!node->IsVisible)
18989
0
    {
18990
0
        ImGuiDockNode* ancestor_node = node;
18991
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18992
0
            ancestor_node = ancestor_node->ParentNode;
18993
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18994
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18995
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18996
0
    }
18997
18998
    // Add window to node
18999
0
    bool node_was_visible = node->IsVisible;
19000
0
    DockNodeAddWindow(node, window, true);
19001
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19002
0
    IM_ASSERT(node == window->DockNode);
19003
0
    return node;
19004
0
}
19005
19006
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19007
0
{
19008
0
    ImGuiContext& g = *GImGui;
19009
19010
    // Clear fields ahead so most early-out paths don't have to do it
19011
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19012
19013
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19014
0
    if (auto_dock_node)
19015
0
    {
19016
0
        if (window->DockId == 0)
19017
0
        {
19018
0
            IM_ASSERT(window->DockNode == NULL);
19019
0
            window->DockId = DockContextGenNodeID(&g);
19020
0
        }
19021
0
    }
19022
0
    else
19023
0
    {
19024
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19025
0
        bool want_undock = false;
19026
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19027
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19028
0
        if (want_undock)
19029
0
        {
19030
0
            DockContextProcessUndockWindow(&g, window);
19031
0
            return;
19032
0
        }
19033
0
    }
19034
19035
    // Bind to our dock node
19036
0
    ImGuiDockNode* node = window->DockNode;
19037
0
    if (node != NULL)
19038
0
        IM_ASSERT(window->DockId == node->ID);
19039
0
    if (window->DockId != 0 && node == NULL)
19040
0
    {
19041
0
        node = DockContextBindNodeToWindow(&g, window);
19042
0
        if (node == NULL)
19043
0
            return;
19044
0
    }
19045
19046
#if 0
19047
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19048
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19049
    {
19050
        DockContextProcessUndockWindow(ctx, window);
19051
        return;
19052
    }
19053
#endif
19054
19055
    // Undock if our dockspace node disappeared
19056
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19057
0
    if (node->LastFrameAlive < g.FrameCount)
19058
0
    {
19059
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19060
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19061
0
        if (root_node->LastFrameAlive < g.FrameCount)
19062
0
            DockContextProcessUndockWindow(&g, window);
19063
0
        else
19064
0
            window->DockIsActive = true;
19065
0
        return;
19066
0
    }
19067
19068
    // Store style overrides
19069
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19070
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19071
19072
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19073
    // and never create neither a host window neither a tab bar.
19074
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19075
0
    if (node->HostWindow == NULL)
19076
0
    {
19077
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19078
0
            window->DockIsActive = true;
19079
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19080
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19081
0
        return;
19082
0
    }
19083
19084
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19085
0
    IM_ASSERT(node->HostWindow);
19086
0
    IM_ASSERT(node->IsLeafNode());
19087
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19088
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19089
19090
    // Undock if we are submitted earlier than the host window
19091
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19092
0
    {
19093
0
        DockContextProcessUndockWindow(&g, window);
19094
0
        return;
19095
0
    }
19096
19097
    // Position/Size window
19098
0
    SetNextWindowPos(node->Pos);
19099
0
    SetNextWindowSize(node->Size);
19100
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19101
0
    window->DockIsActive = true;
19102
0
    window->DockNodeIsVisible = true;
19103
0
    window->DockTabIsVisible = false;
19104
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19105
0
        return;
19106
19107
    // When the window is selected we mark it as visible.
19108
0
    if (node->VisibleWindow == window)
19109
0
        window->DockTabIsVisible = true;
19110
19111
    // Update window flag
19112
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19113
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19114
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19115
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19116
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19117
0
    else
19118
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19119
19120
    // Save new dock order only if the window has been visible once already
19121
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19122
0
    if (node->TabBar && window->WasActive)
19123
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19124
19125
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19126
0
        *p_open = false;
19127
19128
    // Update ChildId to allow returning from Child to Parent with Escape
19129
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19130
0
    window->ChildId = parent_window->GetID(window->Name);
19131
0
}
19132
19133
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19134
6
{
19135
6
    ImGuiContext& g = *GImGui;
19136
6
    IM_ASSERT(g.ActiveId == window->MoveId);
19137
6
    IM_ASSERT(g.MovingWindow == window);
19138
6
    IM_ASSERT(g.CurrentWindow == window);
19139
19140
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19141
6
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19142
0
    {
19143
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19144
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19145
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19146
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19147
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19148
0
        return;
19149
0
    }
19150
19151
6
    g.LastItemData.ID = window->MoveId;
19152
6
    window = window->RootWindowDockTree;
19153
6
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19154
6
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19155
6
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
19156
0
    {
19157
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19158
0
        EndDragDropSource();
19159
19160
        // Store style overrides
19161
0
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19162
0
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19163
0
    }
19164
6
}
19165
19166
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19167
0
{
19168
0
    ImGuiContext& g = *GImGui;
19169
19170
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19171
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19172
0
    if (!g.DragDropActive)
19173
0
        return;
19174
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19175
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19176
0
        return;
19177
19178
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19179
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19180
0
    const ImGuiPayload* payload = &g.DragDropPayload;
19181
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19182
0
    {
19183
0
        EndDragDropTarget();
19184
0
        return;
19185
0
    }
19186
19187
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19188
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19189
0
    {
19190
        // Select target node
19191
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19192
0
        bool dock_into_floating_window = false;
19193
0
        ImGuiDockNode* node = NULL;
19194
0
        if (window->DockNodeAsHost)
19195
0
        {
19196
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19197
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19198
19199
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19200
            // In this case we need to fallback into any leaf mode, possibly the central node.
19201
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19202
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19203
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19204
0
        }
19205
0
        else
19206
0
        {
19207
0
            if (window->DockNode)
19208
0
                node = window->DockNode;
19209
0
            else
19210
0
                dock_into_floating_window = true; // Dock into a regular window
19211
0
        }
19212
19213
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19214
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19215
19216
        // Preview docking request and find out split direction/ratio
19217
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19218
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19219
0
        if (do_preview && (node != NULL || dock_into_floating_window))
19220
0
        {
19221
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19222
0
            ImGuiDockPreviewData split_inner;
19223
0
            ImGuiDockPreviewData split_outer;
19224
0
            ImGuiDockPreviewData* split_data = &split_inner;
19225
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19226
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19227
0
                {
19228
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19229
0
                    if (split_outer.IsSplitDirExplicit)
19230
0
                        split_data = &split_outer;
19231
0
                }
19232
0
            if (!node || node->IsLeafNode())
19233
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19234
0
            if (split_data == &split_outer)
19235
0
                split_inner.IsDropAllowed = false;
19236
19237
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19238
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19239
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19240
19241
            // Queue docking request
19242
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19243
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19244
0
        }
19245
0
    }
19246
0
    EndDragDropTarget();
19247
0
}
19248
19249
//-----------------------------------------------------------------------------
19250
// Docking: Settings
19251
//-----------------------------------------------------------------------------
19252
// - DockSettingsRenameNodeReferences()
19253
// - DockSettingsRemoveNodeReferences()
19254
// - DockSettingsFindNodeSettings()
19255
// - DockSettingsHandler_ApplyAll()
19256
// - DockSettingsHandler_ReadOpen()
19257
// - DockSettingsHandler_ReadLine()
19258
// - DockSettingsHandler_DockNodeToSettings()
19259
// - DockSettingsHandler_WriteAll()
19260
//-----------------------------------------------------------------------------
19261
19262
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19263
0
{
19264
0
    ImGuiContext& g = *GImGui;
19265
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19266
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19267
0
    {
19268
0
        ImGuiWindow* window = g.Windows[window_n];
19269
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19270
0
            window->DockId = new_node_id;
19271
0
    }
19272
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19273
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19274
0
        if (settings->DockId == old_node_id)
19275
0
            settings->DockId = new_node_id;
19276
0
}
19277
19278
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19279
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19280
0
{
19281
0
    ImGuiContext& g = *GImGui;
19282
0
    int found = 0;
19283
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19284
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19285
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19286
0
            if (settings->DockId == node_ids[node_n])
19287
0
            {
19288
0
                settings->DockId = 0;
19289
0
                settings->DockOrder = -1;
19290
0
                if (++found < node_ids_count)
19291
0
                    break;
19292
0
                return;
19293
0
            }
19294
0
}
19295
19296
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19297
0
{
19298
    // FIXME-OPT
19299
0
    ImGuiDockContext* dc = &ctx->DockContext;
19300
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19301
0
        if (dc->NodesSettings[n].ID == id)
19302
0
            return &dc->NodesSettings[n];
19303
0
    return NULL;
19304
0
}
19305
19306
// Clear settings data
19307
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19308
0
{
19309
0
    ImGuiDockContext* dc = &ctx->DockContext;
19310
0
    dc->NodesSettings.clear();
19311
0
    DockContextClearNodes(ctx, 0, true);
19312
0
}
19313
19314
// Recreate nodes based on settings data
19315
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19316
0
{
19317
    // Prune settings at boot time only
19318
0
    ImGuiDockContext* dc = &ctx->DockContext;
19319
0
    if (ctx->Windows.Size == 0)
19320
0
        DockContextPruneUnusedSettingsNodes(ctx);
19321
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19322
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19323
0
}
19324
19325
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19326
0
{
19327
0
    if (strcmp(name, "Data") != 0)
19328
0
        return NULL;
19329
0
    return (void*)1;
19330
0
}
19331
19332
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19333
0
{
19334
0
    char c = 0;
19335
0
    int x = 0, y = 0;
19336
0
    int r = 0;
19337
19338
    // Parsing, e.g.
19339
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19340
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19341
    // Important: this code expect currently fields in a fixed order.
19342
0
    ImGuiDockNodeSettings node;
19343
0
    line = ImStrSkipBlank(line);
19344
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19345
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19346
0
    else return;
19347
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19348
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19349
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19350
0
    if (node.ParentNodeId == 0)
19351
0
    {
19352
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19353
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19354
0
    }
19355
0
    else
19356
0
    {
19357
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19358
0
    }
19359
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19360
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19361
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19362
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19363
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19364
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19365
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19366
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19367
0
    if (node.ParentNodeId != 0)
19368
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19369
0
            node.Depth = parent_settings->Depth + 1;
19370
0
    ctx->DockContext.NodesSettings.push_back(node);
19371
0
}
19372
19373
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19374
0
{
19375
0
    ImGuiDockNodeSettings node_settings;
19376
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19377
0
    node_settings.ID = node->ID;
19378
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19379
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19380
0
    node_settings.SelectedTabId = node->SelectedTabId;
19381
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19382
0
    node_settings.Depth = (char)depth;
19383
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19384
0
    node_settings.Pos = ImVec2ih(node->Pos);
19385
0
    node_settings.Size = ImVec2ih(node->Size);
19386
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19387
0
    dc->NodesSettings.push_back(node_settings);
19388
0
    if (node->ChildNodes[0])
19389
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19390
0
    if (node->ChildNodes[1])
19391
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19392
0
}
19393
19394
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19395
0
{
19396
0
    ImGuiContext& g = *ctx;
19397
0
    ImGuiDockContext* dc = &ctx->DockContext;
19398
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19399
0
        return;
19400
19401
    // Gather settings data
19402
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19403
0
    dc->NodesSettings.resize(0);
19404
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19405
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19406
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19407
0
            if (node->IsRootNode())
19408
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19409
19410
0
    int max_depth = 0;
19411
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19412
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19413
19414
    // Write to text buffer
19415
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19416
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19417
0
    {
19418
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19419
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19420
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19421
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19422
0
        if (node_settings->ParentNodeId)
19423
0
        {
19424
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19425
0
        }
19426
0
        else
19427
0
        {
19428
0
            if (node_settings->ParentWindowId)
19429
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19430
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19431
0
        }
19432
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19433
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19434
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19435
0
            buf->appendf(" NoResize=1");
19436
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19437
0
            buf->appendf(" CentralNode=1");
19438
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19439
0
            buf->appendf(" NoTabBar=1");
19440
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19441
0
            buf->appendf(" HiddenTabBar=1");
19442
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19443
0
            buf->appendf(" NoWindowMenuButton=1");
19444
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19445
0
            buf->appendf(" NoCloseButton=1");
19446
0
        if (node_settings->SelectedTabId)
19447
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19448
19449
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19450
0
        if (g.IO.ConfigDebugIniSettings)
19451
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19452
0
            {
19453
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19454
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19455
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19456
                // Iterate settings so we can give info about windows that didn't exist during the session.
19457
0
                int contains_window = 0;
19458
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19459
0
                    if (settings->DockId == node_settings->ID)
19460
0
                    {
19461
0
                        if (contains_window++ == 0)
19462
0
                            buf->appendf(" ; contains ");
19463
0
                        buf->appendf("'%s' ", settings->GetName());
19464
0
                    }
19465
0
            }
19466
19467
0
        buf->appendf("\n");
19468
0
    }
19469
0
    buf->appendf("\n");
19470
0
}
19471
19472
19473
//-----------------------------------------------------------------------------
19474
// [SECTION] PLATFORM DEPENDENT HELPERS
19475
//-----------------------------------------------------------------------------
19476
19477
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19478
19479
#ifdef _MSC_VER
19480
#pragma comment(lib, "user32")
19481
#pragma comment(lib, "kernel32")
19482
#endif
19483
19484
// Win32 clipboard implementation
19485
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19486
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19487
{
19488
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19489
    g.ClipboardHandlerData.clear();
19490
    if (!::OpenClipboard(NULL))
19491
        return NULL;
19492
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19493
    if (wbuf_handle == NULL)
19494
    {
19495
        ::CloseClipboard();
19496
        return NULL;
19497
    }
19498
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19499
    {
19500
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19501
        g.ClipboardHandlerData.resize(buf_len);
19502
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19503
    }
19504
    ::GlobalUnlock(wbuf_handle);
19505
    ::CloseClipboard();
19506
    return g.ClipboardHandlerData.Data;
19507
}
19508
19509
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19510
{
19511
    if (!::OpenClipboard(NULL))
19512
        return;
19513
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19514
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19515
    if (wbuf_handle == NULL)
19516
    {
19517
        ::CloseClipboard();
19518
        return;
19519
    }
19520
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19521
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19522
    ::GlobalUnlock(wbuf_handle);
19523
    ::EmptyClipboard();
19524
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19525
        ::GlobalFree(wbuf_handle);
19526
    ::CloseClipboard();
19527
}
19528
19529
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19530
19531
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19532
static PasteboardRef main_clipboard = 0;
19533
19534
// OSX clipboard implementation
19535
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19536
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19537
{
19538
    if (!main_clipboard)
19539
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19540
    PasteboardClear(main_clipboard);
19541
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19542
    if (cf_data)
19543
    {
19544
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19545
        CFRelease(cf_data);
19546
    }
19547
}
19548
19549
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19550
{
19551
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19552
    if (!main_clipboard)
19553
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19554
    PasteboardSynchronize(main_clipboard);
19555
19556
    ItemCount item_count = 0;
19557
    PasteboardGetItemCount(main_clipboard, &item_count);
19558
    for (ItemCount i = 0; i < item_count; i++)
19559
    {
19560
        PasteboardItemID item_id = 0;
19561
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19562
        CFArrayRef flavor_type_array = 0;
19563
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19564
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19565
        {
19566
            CFDataRef cf_data;
19567
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19568
            {
19569
                g.ClipboardHandlerData.clear();
19570
                int length = (int)CFDataGetLength(cf_data);
19571
                g.ClipboardHandlerData.resize(length + 1);
19572
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19573
                g.ClipboardHandlerData[length] = 0;
19574
                CFRelease(cf_data);
19575
                return g.ClipboardHandlerData.Data;
19576
            }
19577
        }
19578
    }
19579
    return NULL;
19580
}
19581
19582
#else
19583
19584
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19585
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19586
0
{
19587
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19588
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19589
0
}
19590
19591
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19592
0
{
19593
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19594
0
    g.ClipboardHandlerData.clear();
19595
0
    const char* text_end = text + strlen(text);
19596
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19597
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19598
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19599
0
}
19600
19601
#endif
19602
19603
// Win32 API IME support (for Asian languages, etc.)
19604
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19605
19606
#include <imm.h>
19607
#ifdef _MSC_VER
19608
#pragma comment(lib, "imm32")
19609
#endif
19610
19611
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19612
{
19613
    // Notify OS Input Method Editor of text input position
19614
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19615
    if (hwnd == 0)
19616
        return;
19617
19618
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19619
    if (HIMC himc = ::ImmGetContext(hwnd))
19620
    {
19621
        COMPOSITIONFORM composition_form = {};
19622
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19623
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19624
        composition_form.dwStyle = CFS_FORCE_POSITION;
19625
        ::ImmSetCompositionWindow(himc, &composition_form);
19626
        CANDIDATEFORM candidate_form = {};
19627
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19628
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19629
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19630
        ::ImmSetCandidateWindow(himc, &candidate_form);
19631
        ::ImmReleaseContext(hwnd, himc);
19632
    }
19633
}
19634
19635
#else
19636
19637
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19638
19639
#endif
19640
19641
//-----------------------------------------------------------------------------
19642
// [SECTION] METRICS/DEBUGGER WINDOW
19643
//-----------------------------------------------------------------------------
19644
// - DebugRenderViewportThumbnail() [Internal]
19645
// - RenderViewportsThumbnails() [Internal]
19646
// - DebugTextEncoding()
19647
// - MetricsHelpMarker() [Internal]
19648
// - ShowFontAtlas() [Internal]
19649
// - ShowMetricsWindow()
19650
// - DebugNodeColumns() [Internal]
19651
// - DebugNodeDockNode() [Internal]
19652
// - DebugNodeDrawList() [Internal]
19653
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19654
// - DebugNodeFont() [Internal]
19655
// - DebugNodeFontGlyph() [Internal]
19656
// - DebugNodeStorage() [Internal]
19657
// - DebugNodeTabBar() [Internal]
19658
// - DebugNodeViewport() [Internal]
19659
// - DebugNodeWindow() [Internal]
19660
// - DebugNodeWindowSettings() [Internal]
19661
// - DebugNodeWindowsList() [Internal]
19662
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19663
//-----------------------------------------------------------------------------
19664
19665
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19666
19667
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19668
0
{
19669
0
    ImGuiContext& g = *GImGui;
19670
0
    ImGuiWindow* window = g.CurrentWindow;
19671
19672
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19673
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19674
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19675
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19676
0
    for (ImGuiWindow* thumb_window : g.Windows)
19677
0
    {
19678
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19679
0
            continue;
19680
0
        if (thumb_window->Viewport != viewport)
19681
0
            continue;
19682
19683
0
        ImRect thumb_r = thumb_window->Rect();
19684
0
        ImRect title_r = thumb_window->TitleBarRect();
19685
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19686
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
19687
0
        thumb_r.ClipWithFull(bb);
19688
0
        title_r.ClipWithFull(bb);
19689
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19690
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19691
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19692
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19693
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19694
0
    }
19695
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19696
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
19697
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
19698
0
}
19699
19700
static void RenderViewportsThumbnails()
19701
0
{
19702
0
    ImGuiContext& g = *GImGui;
19703
0
    ImGuiWindow* window = g.CurrentWindow;
19704
19705
    // Draw monitor and calculate their boundaries
19706
0
    float SCALE = 1.0f / 8.0f;
19707
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19708
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19709
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
19710
0
    ImVec2 p = window->DC.CursorPos;
19711
0
    ImVec2 off = p - bb_full.Min * SCALE;
19712
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19713
0
    {
19714
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
19715
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
19716
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
19717
0
    }
19718
19719
    // Draw viewports
19720
0
    for (ImGuiViewportP* viewport : g.Viewports)
19721
0
    {
19722
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19723
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19724
0
    }
19725
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19726
0
}
19727
19728
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19729
0
{
19730
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19731
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19732
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19733
0
}
19734
19735
// Draw an arbitrary US keyboard layout to visualize translated keys
19736
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19737
0
{
19738
0
    const float scale = ImGui::GetFontSize() / 13.0f;
19739
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
19740
0
    const float  key_rounding = 3.0f * scale;
19741
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
19742
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
19743
0
    const float  key_face_rounding = 2.0f * scale;
19744
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
19745
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19746
0
    const float  key_row_offset = 9.0f * scale;
19747
19748
0
    ImVec2 board_min = GetCursorScreenPos();
19749
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19750
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19751
19752
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19753
0
    const KeyLayoutData keys_to_display[] =
19754
0
    {
19755
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19756
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19757
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19758
0
    };
19759
19760
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19761
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19762
0
    Dummy(board_max - board_min);
19763
0
    if (!IsItemVisible())
19764
0
        return;
19765
0
    draw_list->PushClipRect(board_min, board_max, true);
19766
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19767
0
    {
19768
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19769
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19770
0
        ImVec2 key_max = key_min + key_size;
19771
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19772
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19773
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19774
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19775
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19776
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19777
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19778
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19779
0
        if (IsKeyDown(key_data->Key))
19780
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19781
0
    }
19782
0
    draw_list->PopClipRect();
19783
0
}
19784
19785
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19786
void ImGui::DebugTextEncoding(const char* str)
19787
0
{
19788
0
    Text("Text: \"%s\"", str);
19789
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19790
0
        return;
19791
0
    TableSetupColumn("Offset");
19792
0
    TableSetupColumn("UTF-8");
19793
0
    TableSetupColumn("Glyph");
19794
0
    TableSetupColumn("Codepoint");
19795
0
    TableHeadersRow();
19796
0
    for (const char* p = str; *p != 0; )
19797
0
    {
19798
0
        unsigned int c;
19799
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19800
0
        TableNextColumn();
19801
0
        Text("%d", (int)(p - str));
19802
0
        TableNextColumn();
19803
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19804
0
        {
19805
0
            if (byte_index > 0)
19806
0
                SameLine();
19807
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19808
0
        }
19809
0
        TableNextColumn();
19810
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19811
0
            TextUnformatted(p, p + c_utf8_len);
19812
0
        else
19813
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19814
0
        TableNextColumn();
19815
0
        Text("U+%04X", (int)c);
19816
0
        p += c_utf8_len;
19817
0
    }
19818
0
    EndTable();
19819
0
}
19820
19821
static void DebugFlashStyleColorStop()
19822
0
{
19823
0
    ImGuiContext& g = *GImGui;
19824
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
19825
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
19826
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
19827
0
}
19828
19829
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
19830
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
19831
0
{
19832
0
    ImGuiContext& g = *GImGui;
19833
0
    DebugFlashStyleColorStop();
19834
0
    g.DebugFlashStyleColorTime = 0.5f;
19835
0
    g.DebugFlashStyleColorIdx = idx;
19836
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
19837
0
}
19838
19839
void ImGui::UpdateDebugToolFlashStyleColor()
19840
22.2k
{
19841
22.2k
    ImGuiContext& g = *GImGui;
19842
22.2k
    if (g.DebugFlashStyleColorTime <= 0.0f)
19843
22.2k
        return;
19844
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
19845
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
19846
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
19847
0
        DebugFlashStyleColorStop();
19848
0
}
19849
19850
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19851
static void MetricsHelpMarker(const char* desc)
19852
0
{
19853
0
    ImGui::TextDisabled("(?)");
19854
0
    if (ImGui::BeginItemTooltip())
19855
0
    {
19856
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19857
0
        ImGui::TextUnformatted(desc);
19858
0
        ImGui::PopTextWrapPos();
19859
0
        ImGui::EndTooltip();
19860
0
    }
19861
0
}
19862
19863
// [DEBUG] List fonts in a font atlas and display its texture
19864
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19865
0
{
19866
0
    for (ImFont* font : atlas->Fonts)
19867
0
    {
19868
0
        PushID(font);
19869
0
        DebugNodeFont(font);
19870
0
        PopID();
19871
0
    }
19872
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19873
0
    {
19874
0
        ImGuiContext& g = *GImGui;
19875
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19876
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19877
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19878
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19879
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19880
0
        TreePop();
19881
0
    }
19882
0
}
19883
19884
void ImGui::ShowMetricsWindow(bool* p_open)
19885
0
{
19886
0
    ImGuiContext& g = *GImGui;
19887
0
    ImGuiIO& io = g.IO;
19888
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19889
0
    if (cfg->ShowDebugLog)
19890
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19891
0
    if (cfg->ShowIDStackTool)
19892
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19893
19894
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19895
0
    {
19896
0
        End();
19897
0
        return;
19898
0
    }
19899
19900
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
19901
0
    DebugBreakClearData();
19902
19903
    // Basic info
19904
0
    Text("Dear ImGui %s", GetVersion());
19905
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19906
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19907
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19908
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19909
19910
0
    Separator();
19911
19912
    // Debugging enums
19913
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19914
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19915
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19916
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19917
0
    if (cfg->ShowWindowsRectsType < 0)
19918
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19919
0
    if (cfg->ShowTablesRectsType < 0)
19920
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19921
19922
0
    struct Funcs
19923
0
    {
19924
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19925
0
        {
19926
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19927
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19928
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19929
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19930
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19931
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19932
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19933
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19934
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19935
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19936
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19937
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19938
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19939
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19940
0
            IM_ASSERT(0);
19941
0
            return ImRect();
19942
0
        }
19943
19944
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19945
0
        {
19946
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19947
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19948
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19949
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19950
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19951
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19952
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19953
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19954
0
            IM_ASSERT(0);
19955
0
            return ImRect();
19956
0
        }
19957
0
    };
19958
19959
    // Tools
19960
0
    if (TreeNode("Tools"))
19961
0
    {
19962
        // Debug Break features
19963
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19964
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
19965
0
        SameLine();
19966
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19967
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19968
0
            DebugStartItemPicker();
19969
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
19970
19971
0
        SeparatorText("Visualize");
19972
19973
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19974
0
        SameLine();
19975
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19976
19977
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19978
0
        SameLine();
19979
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19980
19981
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19982
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19983
0
        SameLine();
19984
0
        SetNextItemWidth(GetFontSize() * 12);
19985
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19986
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19987
0
        {
19988
0
            BulletText("'%s':", g.NavWindow->Name);
19989
0
            Indent();
19990
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19991
0
            {
19992
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19993
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19994
0
            }
19995
0
            Unindent();
19996
0
        }
19997
19998
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19999
0
        SameLine();
20000
0
        SetNextItemWidth(GetFontSize() * 12);
20001
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20002
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20003
0
        {
20004
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20005
0
            {
20006
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20007
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20008
0
                    continue;
20009
20010
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20011
0
                if (IsItemHovered())
20012
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20013
0
                Indent();
20014
0
                char buf[128];
20015
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20016
0
                {
20017
0
                    if (rect_n >= TRT_ColumnsRect)
20018
0
                    {
20019
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20020
0
                            continue;
20021
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20022
0
                        {
20023
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20024
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20025
0
                            Selectable(buf);
20026
0
                            if (IsItemHovered())
20027
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20028
0
                        }
20029
0
                    }
20030
0
                    else
20031
0
                    {
20032
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20033
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20034
0
                        Selectable(buf);
20035
0
                        if (IsItemHovered())
20036
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20037
0
                    }
20038
0
                }
20039
0
                Unindent();
20040
0
            }
20041
0
        }
20042
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20043
20044
0
        SeparatorText("Validate");
20045
20046
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20047
0
        SameLine();
20048
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20049
20050
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20051
0
        SameLine();
20052
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20053
0
        if (cfg->ShowTextEncodingViewer)
20054
0
        {
20055
0
            static char buf[64] = "";
20056
0
            SetNextItemWidth(-FLT_MIN);
20057
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20058
0
            if (buf[0] != 0)
20059
0
                DebugTextEncoding(buf);
20060
0
        }
20061
20062
0
        TreePop();
20063
0
    }
20064
20065
    // Windows
20066
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20067
0
    {
20068
        //SetNextItemOpen(true, ImGuiCond_Once);
20069
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20070
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20071
0
        if (TreeNode("By submission order (begin stack)"))
20072
0
        {
20073
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20074
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20075
0
            temp_buffer.resize(0);
20076
0
            for (ImGuiWindow* window : g.Windows)
20077
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20078
0
                    temp_buffer.push_back(window);
20079
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20080
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20081
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20082
0
            TreePop();
20083
0
        }
20084
20085
0
        TreePop();
20086
0
    }
20087
20088
    // DrawLists
20089
0
    int drawlist_count = 0;
20090
0
    for (ImGuiViewportP* viewport : g.Viewports)
20091
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20092
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20093
0
    {
20094
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20095
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20096
0
        for (ImGuiViewportP* viewport : g.Viewports)
20097
0
        {
20098
0
            bool viewport_has_drawlist = false;
20099
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20100
0
            {
20101
0
                if (!viewport_has_drawlist)
20102
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20103
0
                viewport_has_drawlist = true;
20104
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20105
0
            }
20106
0
        }
20107
0
        TreePop();
20108
0
    }
20109
20110
    // Viewports
20111
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20112
0
    {
20113
0
        cfg->HighlightMonitorIdx = -1;
20114
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20115
0
        SameLine();
20116
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20117
0
        if (open)
20118
0
        {
20119
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20120
0
            {
20121
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20122
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20123
0
                    i, mon.DpiScale * 100.0f,
20124
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20125
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20126
0
                if (IsItemHovered())
20127
0
                    cfg->HighlightMonitorIdx = i;
20128
0
            }
20129
0
            TreePop();
20130
0
        }
20131
20132
0
        SetNextItemOpen(true, ImGuiCond_Once);
20133
0
        if (TreeNode("Windows Minimap"))
20134
0
        {
20135
0
            RenderViewportsThumbnails();
20136
0
            TreePop();
20137
0
        }
20138
0
        cfg->HighlightViewportID = 0;
20139
20140
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20141
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20142
0
        {
20143
0
            static ImVector<ImGuiViewportP*> viewports;
20144
0
            viewports.resize(g.Viewports.Size);
20145
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20146
0
            if (viewports.Size > 1)
20147
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20148
0
            for (ImGuiViewportP* viewport : viewports)
20149
0
            {
20150
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20151
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20152
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20153
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20154
0
                if (IsItemHovered())
20155
0
                    cfg->HighlightViewportID = viewport->ID;
20156
0
            }
20157
0
            TreePop();
20158
0
        }
20159
20160
0
        for (ImGuiViewportP* viewport : g.Viewports)
20161
0
            DebugNodeViewport(viewport);
20162
0
        TreePop();
20163
0
    }
20164
20165
    // Details for Popups
20166
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20167
0
    {
20168
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20169
0
        {
20170
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20171
0
            ImGuiWindow* window = popup_data.Window;
20172
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20173
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20174
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20175
0
        }
20176
0
        TreePop();
20177
0
    }
20178
20179
    // Details for TabBars
20180
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20181
0
    {
20182
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20183
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20184
0
            {
20185
0
                PushID(tab_bar);
20186
0
                DebugNodeTabBar(tab_bar, "TabBar");
20187
0
                PopID();
20188
0
            }
20189
0
        TreePop();
20190
0
    }
20191
20192
    // Details for Tables
20193
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20194
0
    {
20195
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20196
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20197
0
                DebugNodeTable(table);
20198
0
        TreePop();
20199
0
    }
20200
20201
    // Details for Fonts
20202
0
    ImFontAtlas* atlas = g.IO.Fonts;
20203
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20204
0
    {
20205
0
        ShowFontAtlas(atlas);
20206
0
        TreePop();
20207
0
    }
20208
20209
    // Details for InputText
20210
0
    if (TreeNode("InputText"))
20211
0
    {
20212
0
        DebugNodeInputTextState(&g.InputTextState);
20213
0
        TreePop();
20214
0
    }
20215
20216
    // Details for TypingSelect
20217
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20218
0
    {
20219
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20220
0
        TreePop();
20221
0
    }
20222
20223
    // Details for Docking
20224
0
#ifdef IMGUI_HAS_DOCK
20225
0
    if (TreeNode("Docking"))
20226
0
    {
20227
0
        static bool root_nodes_only = true;
20228
0
        ImGuiDockContext* dc = &g.DockContext;
20229
0
        Checkbox("List root nodes", &root_nodes_only);
20230
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20231
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20232
0
        SameLine();
20233
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20234
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20235
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20236
0
                if (!root_nodes_only || node->IsRootNode())
20237
0
                    DebugNodeDockNode(node, "Node");
20238
0
        TreePop();
20239
0
    }
20240
0
#endif // #ifdef IMGUI_HAS_DOCK
20241
20242
    // Settings
20243
0
    if (TreeNode("Settings"))
20244
0
    {
20245
0
        if (SmallButton("Clear"))
20246
0
            ClearIniSettings();
20247
0
        SameLine();
20248
0
        if (SmallButton("Save to memory"))
20249
0
            SaveIniSettingsToMemory();
20250
0
        SameLine();
20251
0
        if (SmallButton("Save to disk"))
20252
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20253
0
        SameLine();
20254
0
        if (g.IO.IniFilename)
20255
0
            Text("\"%s\"", g.IO.IniFilename);
20256
0
        else
20257
0
            TextUnformatted("<NULL>");
20258
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20259
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20260
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20261
0
        {
20262
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20263
0
                BulletText("\"%s\"", handler.TypeName);
20264
0
            TreePop();
20265
0
        }
20266
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20267
0
        {
20268
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20269
0
                DebugNodeWindowSettings(settings);
20270
0
            TreePop();
20271
0
        }
20272
20273
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20274
0
        {
20275
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20276
0
                DebugNodeTableSettings(settings);
20277
0
            TreePop();
20278
0
        }
20279
20280
0
#ifdef IMGUI_HAS_DOCK
20281
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20282
0
        {
20283
0
            ImGuiDockContext* dc = &g.DockContext;
20284
0
            Text("In SettingsWindows:");
20285
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20286
0
                if (settings->DockId != 0)
20287
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20288
0
            Text("In SettingsNodes:");
20289
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20290
0
            {
20291
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20292
0
                const char* selected_tab_name = NULL;
20293
0
                if (settings->SelectedTabId)
20294
0
                {
20295
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20296
0
                        selected_tab_name = window->Name;
20297
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20298
0
                        selected_tab_name = window_settings->GetName();
20299
0
                }
20300
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20301
0
            }
20302
0
            TreePop();
20303
0
        }
20304
0
#endif // #ifdef IMGUI_HAS_DOCK
20305
20306
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20307
0
        {
20308
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20309
0
            TreePop();
20310
0
        }
20311
0
        TreePop();
20312
0
    }
20313
20314
    // Settings
20315
0
    if (TreeNode("Memory allocations"))
20316
0
    {
20317
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20318
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20319
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20320
0
        Text("Recent frames with allocations:");
20321
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20322
0
        for (int n = buf_size - 1; n >= 0; n--)
20323
0
        {
20324
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20325
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20326
0
        }
20327
0
        TreePop();
20328
0
    }
20329
20330
0
    if (TreeNode("Inputs"))
20331
0
    {
20332
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20333
0
        {
20334
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20335
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20336
0
            Indent();
20337
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20338
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20339
#else
20340
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20341
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20342
#endif
20343
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20344
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20345
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20346
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20347
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20348
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20349
0
            Unindent();
20350
0
        }
20351
20352
0
        Text("MOUSE STATE");
20353
0
        {
20354
0
            Indent();
20355
0
            if (IsMousePosValid())
20356
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20357
0
            else
20358
0
                Text("Mouse pos: <INVALID>");
20359
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20360
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20361
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20362
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20363
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20364
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20365
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20366
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20367
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20368
0
            Unindent();
20369
0
        }
20370
20371
0
        Text("MOUSE WHEELING");
20372
0
        {
20373
0
            Indent();
20374
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20375
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20376
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20377
0
            Unindent();
20378
0
        }
20379
20380
0
        Text("KEY OWNERS");
20381
0
        {
20382
0
            Indent();
20383
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20384
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20385
0
                {
20386
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20387
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
20388
0
                        continue;
20389
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20390
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20391
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20392
0
                }
20393
0
            EndChild();
20394
0
            Unindent();
20395
0
        }
20396
0
        Text("SHORTCUT ROUTING");
20397
0
        SameLine();
20398
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20399
0
        {
20400
0
            Indent();
20401
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20402
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20403
0
                {
20404
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20405
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20406
0
                    {
20407
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20408
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20409
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20410
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20411
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20412
0
                        {
20413
0
                            SameLine();
20414
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20415
0
                                g.DebugBreakInShortcutRouting = key_chord;
20416
0
                        }
20417
0
                        idx = routing_data->NextEntryIndex;
20418
0
                    }
20419
0
                }
20420
0
            EndChild();
20421
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20422
0
            Unindent();
20423
0
        }
20424
0
        TreePop();
20425
0
    }
20426
20427
0
    if (TreeNode("Internal state"))
20428
0
    {
20429
0
        Text("WINDOWING");
20430
0
        Indent();
20431
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20432
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20433
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20434
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20435
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20436
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20437
0
        Unindent();
20438
20439
0
        Text("ITEMS");
20440
0
        Indent();
20441
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20442
0
        DebugLocateItemOnHover(g.ActiveId);
20443
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20444
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20445
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20446
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20447
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20448
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20449
0
        Unindent();
20450
20451
0
        Text("NAV,FOCUS");
20452
0
        Indent();
20453
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20454
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20455
0
        DebugLocateItemOnHover(g.NavId);
20456
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20457
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20458
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20459
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20460
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20461
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20462
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20463
0
        Text("NavFocusRoute[] = ");
20464
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20465
0
        {
20466
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20467
0
            SameLine(0.0f, 0.0f);
20468
0
            Text("0x%08X/", focus_scope.ID);
20469
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20470
0
        }
20471
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20472
0
        Unindent();
20473
20474
0
        TreePop();
20475
0
    }
20476
20477
    // Overlay: Display windows Rectangles and Begin Order
20478
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20479
0
    {
20480
0
        for (ImGuiWindow* window : g.Windows)
20481
0
        {
20482
0
            if (!window->WasActive)
20483
0
                continue;
20484
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20485
0
            if (cfg->ShowWindowsRects)
20486
0
            {
20487
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20488
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20489
0
            }
20490
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20491
0
            {
20492
0
                char buf[32];
20493
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20494
0
                float font_size = GetFontSize();
20495
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20496
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20497
0
            }
20498
0
        }
20499
0
    }
20500
20501
    // Overlay: Display Tables Rectangles
20502
0
    if (cfg->ShowTablesRects)
20503
0
    {
20504
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20505
0
        {
20506
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20507
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20508
0
                continue;
20509
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20510
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20511
0
            {
20512
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20513
0
                {
20514
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20515
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20516
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20517
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20518
0
                }
20519
0
            }
20520
0
            else
20521
0
            {
20522
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20523
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20524
0
            }
20525
0
        }
20526
0
    }
20527
20528
0
#ifdef IMGUI_HAS_DOCK
20529
    // Overlay: Display Docking info
20530
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20531
0
    {
20532
0
        char buf[64] = "";
20533
0
        char* p = buf;
20534
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20535
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20536
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20537
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20538
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20539
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20540
0
        int depth = DockNodeGetDepth(node);
20541
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20542
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20543
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20544
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20545
0
    }
20546
0
#endif // #ifdef IMGUI_HAS_DOCK
20547
20548
0
    End();
20549
0
}
20550
20551
void ImGui::DebugBreakClearData()
20552
0
{
20553
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
20554
0
    ImGuiContext& g = *GImGui;
20555
0
    g.DebugBreakInWindow = 0;
20556
0
    g.DebugBreakInTable = 0;
20557
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
20558
0
}
20559
20560
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20561
0
{
20562
0
    if (!BeginItemTooltip())
20563
0
        return;
20564
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
20565
0
    Separator();
20566
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20567
0
    Separator();
20568
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20569
0
    EndTooltip();
20570
0
}
20571
20572
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20573
// In order to reduce interferences with the contents we are trying to debug into.
20574
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20575
0
{
20576
0
    ImGuiWindow* window = GetCurrentWindow();
20577
0
    if (window->SkipItems)
20578
0
        return false;
20579
20580
0
    ImGuiContext& g = *GImGui;
20581
0
    const ImGuiID id = window->GetID(label);
20582
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
20583
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20584
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20585
20586
0
    const ImRect bb(pos, pos + size);
20587
0
    ItemSize(size, 0.0f);
20588
0
    if (!ItemAdd(bb, id))
20589
0
        return false;
20590
20591
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
20592
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
20593
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
20594
0
    DebugBreakButtonTooltip(false, description_of_location);
20595
20596
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
20597
0
    ImVec4 hsv;
20598
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
20599
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
20600
20601
0
    RenderNavHighlight(bb, id);
20602
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
20603
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
20604
20605
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
20606
0
    return pressed;
20607
0
}
20608
20609
// [DEBUG] Display contents of Columns
20610
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20611
0
{
20612
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20613
0
        return;
20614
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20615
0
    for (ImGuiOldColumnData& column : columns->Columns)
20616
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20617
0
    TreePop();
20618
0
}
20619
20620
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20621
0
{
20622
0
    using namespace ImGui;
20623
0
    PushID(label);
20624
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20625
0
    Text("%s:", label);
20626
0
    if (!enabled)
20627
0
        BeginDisabled();
20628
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20629
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20630
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20631
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20632
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20633
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20634
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20635
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
20636
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20637
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20638
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20639
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20640
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20641
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20642
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20643
0
    if (!enabled)
20644
0
        EndDisabled();
20645
0
    PopStyleVar();
20646
0
    PopID();
20647
0
}
20648
20649
// [DEBUG] Display contents of ImDockNode
20650
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20651
0
{
20652
0
    ImGuiContext& g = *GImGui;
20653
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20654
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
20655
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20656
0
    bool open;
20657
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20658
0
    if (node->Windows.Size > 0)
20659
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20660
0
    else
20661
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20662
0
    if (!is_alive) { PopStyleColor(); }
20663
0
    if (is_active && IsItemHovered())
20664
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20665
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20666
0
    if (open)
20667
0
    {
20668
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20669
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20670
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20671
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20672
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20673
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20674
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20675
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20676
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20677
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20678
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20679
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20680
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20681
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20682
0
        {
20683
0
            if (BeginTable("flags", 4))
20684
0
            {
20685
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20686
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20687
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20688
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20689
0
                EndTable();
20690
0
            }
20691
0
            TreePop();
20692
0
        }
20693
0
        if (node->ParentNode)
20694
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20695
0
        if (node->ChildNodes[0])
20696
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20697
0
        if (node->ChildNodes[1])
20698
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20699
0
        if (node->TabBar)
20700
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20701
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20702
20703
0
        TreePop();
20704
0
    }
20705
0
}
20706
20707
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
20708
0
{
20709
0
    union { void* ptr; int integer; } tex_id_opaque;
20710
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
20711
0
    if (sizeof(tex_id) >= sizeof(void*))
20712
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
20713
0
    else
20714
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
20715
0
}
20716
20717
// [DEBUG] Display contents of ImDrawList
20718
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20719
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20720
0
{
20721
0
    ImGuiContext& g = *GImGui;
20722
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20723
0
    int cmd_count = draw_list->CmdBuffer.Size;
20724
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20725
0
        cmd_count--;
20726
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20727
0
    if (draw_list == GetWindowDrawList())
20728
0
    {
20729
0
        SameLine();
20730
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20731
0
        if (node_open)
20732
0
            TreePop();
20733
0
        return;
20734
0
    }
20735
20736
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20737
0
    if (window && IsItemHovered() && fg_draw_list)
20738
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20739
0
    if (!node_open)
20740
0
        return;
20741
20742
0
    if (window && !window->WasActive)
20743
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20744
20745
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20746
0
    {
20747
0
        if (pcmd->UserCallback)
20748
0
        {
20749
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20750
0
            continue;
20751
0
        }
20752
20753
0
        char texid_desc[20];
20754
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
20755
0
        char buf[300];
20756
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20757
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20758
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20759
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20760
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20761
0
        if (!pcmd_node_open)
20762
0
            continue;
20763
20764
        // Calculate approximate coverage area (touched pixel count)
20765
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20766
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20767
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20768
0
        float total_area = 0.0f;
20769
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20770
0
        {
20771
0
            ImVec2 triangle[3];
20772
0
            for (int n = 0; n < 3; n++, idx_n++)
20773
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20774
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20775
0
        }
20776
20777
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20778
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20779
0
        Selectable(buf);
20780
0
        if (IsItemHovered() && fg_draw_list)
20781
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20782
20783
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20784
0
        ImGuiListClipper clipper;
20785
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20786
0
        while (clipper.Step())
20787
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20788
0
            {
20789
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20790
0
                ImVec2 triangle[3];
20791
0
                for (int n = 0; n < 3; n++, idx_i++)
20792
0
                {
20793
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20794
0
                    triangle[n] = v.pos;
20795
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20796
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20797
0
                }
20798
20799
0
                Selectable(buf, false);
20800
0
                if (fg_draw_list && IsItemHovered())
20801
0
                {
20802
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20803
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20804
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20805
0
                    fg_draw_list->Flags = backup_flags;
20806
0
                }
20807
0
            }
20808
0
        TreePop();
20809
0
    }
20810
0
    TreePop();
20811
0
}
20812
20813
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20814
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20815
0
{
20816
0
    IM_ASSERT(show_mesh || show_aabb);
20817
20818
    // Draw wire-frame version of all triangles
20819
0
    ImRect clip_rect = draw_cmd->ClipRect;
20820
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20821
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20822
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20823
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20824
0
    {
20825
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20826
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20827
20828
0
        ImVec2 triangle[3];
20829
0
        for (int n = 0; n < 3; n++, idx_n++)
20830
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20831
0
        if (show_mesh)
20832
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20833
0
    }
20834
    // Draw bounding boxes
20835
0
    if (show_aabb)
20836
0
    {
20837
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20838
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20839
0
    }
20840
0
    out_draw_list->Flags = backup_flags;
20841
0
}
20842
20843
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20844
void ImGui::DebugNodeFont(ImFont* font)
20845
0
{
20846
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20847
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20848
0
    SameLine();
20849
0
    if (SmallButton("Set as default"))
20850
0
        GetIO().FontDefault = font;
20851
0
    if (!opened)
20852
0
        return;
20853
20854
    // Display preview text
20855
0
    PushFont(font);
20856
0
    Text("The quick brown fox jumps over the lazy dog");
20857
0
    PopFont();
20858
20859
    // Display details
20860
0
    SetNextItemWidth(GetFontSize() * 8);
20861
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20862
0
    SameLine(); MetricsHelpMarker(
20863
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
20864
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20865
0
        "You may oversample them to get some flexibility with scaling. "
20866
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20867
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20868
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20869
0
    char c_str[5];
20870
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20871
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20872
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20873
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20874
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20875
0
        if (font->ConfigData)
20876
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20877
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20878
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20879
20880
    // Display all glyphs of the fonts in separate pages of 256 characters
20881
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20882
0
    {
20883
0
        ImDrawList* draw_list = GetWindowDrawList();
20884
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20885
0
        const float cell_size = font->FontSize * 1;
20886
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20887
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20888
0
        {
20889
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20890
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20891
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20892
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20893
0
            {
20894
0
                base += 4096 - 256;
20895
0
                continue;
20896
0
            }
20897
20898
0
            int count = 0;
20899
0
            for (unsigned int n = 0; n < 256; n++)
20900
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20901
0
                    count++;
20902
0
            if (count <= 0)
20903
0
                continue;
20904
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20905
0
                continue;
20906
20907
            // Draw a 16x16 grid of glyphs
20908
0
            ImVec2 base_pos = GetCursorScreenPos();
20909
0
            for (unsigned int n = 0; n < 256; n++)
20910
0
            {
20911
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20912
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20913
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20914
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20915
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20916
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20917
0
                if (!glyph)
20918
0
                    continue;
20919
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20920
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20921
0
                {
20922
0
                    DebugNodeFontGlyph(font, glyph);
20923
0
                    EndTooltip();
20924
0
                }
20925
0
            }
20926
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20927
0
            TreePop();
20928
0
        }
20929
0
        TreePop();
20930
0
    }
20931
0
    TreePop();
20932
0
}
20933
20934
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20935
0
{
20936
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20937
0
    Separator();
20938
0
    Text("Visible: %d", glyph->Visible);
20939
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20940
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20941
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20942
0
}
20943
20944
// [DEBUG] Display contents of ImGuiStorage
20945
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20946
0
{
20947
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20948
0
        return;
20949
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20950
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20951
0
    TreePop();
20952
0
}
20953
20954
// [DEBUG] Display contents of ImGuiTabBar
20955
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20956
0
{
20957
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20958
0
    char buf[256];
20959
0
    char* p = buf;
20960
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20961
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20962
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20963
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20964
0
    {
20965
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20966
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20967
0
    }
20968
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20969
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20970
0
    bool open = TreeNode(label, "%s", buf);
20971
0
    if (!is_active) { PopStyleColor(); }
20972
0
    if (is_active && IsItemHovered())
20973
0
    {
20974
0
        ImDrawList* draw_list = GetForegroundDrawList();
20975
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20976
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20977
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20978
0
    }
20979
0
    if (open)
20980
0
    {
20981
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20982
0
        {
20983
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20984
0
            PushID(tab);
20985
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20986
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20987
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20988
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20989
0
            PopID();
20990
0
        }
20991
0
        TreePop();
20992
0
    }
20993
0
}
20994
20995
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20996
0
{
20997
0
    ImGuiContext& g = *GImGui;
20998
0
    SetNextItemOpen(true, ImGuiCond_Once);
20999
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21000
0
    if (IsItemHovered())
21001
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21002
0
    if (open)
21003
0
    {
21004
0
        ImGuiWindowFlags flags = viewport->Flags;
21005
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21006
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21007
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21008
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21009
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21010
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21011
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21012
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21013
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21014
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21015
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21016
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21017
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21018
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21019
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21020
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21021
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21022
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21023
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21024
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21025
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21026
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21027
0
        TreePop();
21028
0
    }
21029
0
}
21030
21031
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21032
0
{
21033
0
    if (window == NULL)
21034
0
    {
21035
0
        BulletText("%s: NULL", label);
21036
0
        return;
21037
0
    }
21038
21039
0
    ImGuiContext& g = *GImGui;
21040
0
    const bool is_active = window->WasActive;
21041
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21042
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21043
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21044
0
    if (!is_active) { PopStyleColor(); }
21045
0
    if (IsItemHovered() && is_active)
21046
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21047
0
    if (!open)
21048
0
        return;
21049
21050
0
    if (window->MemoryCompacted)
21051
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21052
21053
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21054
0
        g.DebugBreakInWindow = window->ID;
21055
21056
0
    ImGuiWindowFlags flags = window->Flags;
21057
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21058
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21059
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21060
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21061
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21062
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21063
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21064
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21065
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21066
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21067
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21068
0
    {
21069
0
        ImRect r = window->NavRectRel[layer];
21070
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21071
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21072
0
        else
21073
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21074
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21075
0
    }
21076
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21077
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21078
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21079
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21080
21081
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21082
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21083
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21084
0
    if (window->DockNode || window->DockNodeAsHost)
21085
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21086
21087
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21088
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21089
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21090
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21091
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21092
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21093
0
    {
21094
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21095
0
            DebugNodeColumns(&columns);
21096
0
        TreePop();
21097
0
    }
21098
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21099
0
    TreePop();
21100
0
}
21101
21102
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21103
0
{
21104
0
    if (settings->WantDelete)
21105
0
        BeginDisabled();
21106
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21107
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21108
0
    if (settings->WantDelete)
21109
0
        EndDisabled();
21110
0
}
21111
21112
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21113
0
{
21114
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21115
0
        return;
21116
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21117
0
    {
21118
0
        PushID((*windows)[i]);
21119
0
        DebugNodeWindow((*windows)[i], "Window");
21120
0
        PopID();
21121
0
    }
21122
0
    TreePop();
21123
0
}
21124
21125
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21126
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21127
0
{
21128
0
    for (int i = 0; i < windows_size; i++)
21129
0
    {
21130
0
        ImGuiWindow* window = windows[i];
21131
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21132
0
            continue;
21133
0
        char buf[20];
21134
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21135
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21136
0
        DebugNodeWindow(window, buf);
21137
0
        Indent();
21138
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21139
0
        Unindent();
21140
0
    }
21141
0
}
21142
21143
//-----------------------------------------------------------------------------
21144
// [SECTION] DEBUG LOG WINDOW
21145
//-----------------------------------------------------------------------------
21146
21147
void ImGui::DebugLog(const char* fmt, ...)
21148
0
{
21149
0
    va_list args;
21150
0
    va_start(args, fmt);
21151
0
    DebugLogV(fmt, args);
21152
0
    va_end(args);
21153
0
}
21154
21155
void ImGui::DebugLogV(const char* fmt, va_list args)
21156
0
{
21157
0
    ImGuiContext& g = *GImGui;
21158
0
    const int old_size = g.DebugLogBuf.size();
21159
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21160
0
    g.DebugLogBuf.appendfv(fmt, args);
21161
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21162
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21163
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21164
#ifdef IMGUI_ENABLE_TEST_ENGINE
21165
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21166
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
21167
#endif
21168
0
}
21169
21170
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21171
static void SameLineOrWrap(const ImVec2& size)
21172
0
{
21173
0
    ImGuiContext& g = *GImGui;
21174
0
    ImGuiWindow* window = g.CurrentWindow;
21175
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21176
0
    if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21177
0
        ImGui::SameLine();
21178
0
}
21179
21180
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21181
0
{
21182
0
    ImGuiContext& g = *GImGui;
21183
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21184
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21185
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21186
0
    {
21187
0
        g.DebugLogAutoDisableFrames = 2;
21188
0
        g.DebugLogAutoDisableFlags |= flags;
21189
0
    }
21190
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21191
0
}
21192
21193
void ImGui::ShowDebugLogWindow(bool* p_open)
21194
0
{
21195
0
    ImGuiContext& g = *GImGui;
21196
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21197
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21198
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21199
0
    {
21200
0
        End();
21201
0
        return;
21202
0
    }
21203
21204
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21205
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21206
0
    SetItemTooltip("(except InputRouting which is spammy)");
21207
21208
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21209
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21210
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21211
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21212
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21213
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21214
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21215
    //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21216
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21217
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21218
21219
0
    if (SmallButton("Clear"))
21220
0
    {
21221
0
        g.DebugLogBuf.clear();
21222
0
        g.DebugLogIndex.clear();
21223
0
    }
21224
0
    SameLine();
21225
0
    if (SmallButton("Copy"))
21226
0
        SetClipboardText(g.DebugLogBuf.c_str());
21227
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21228
21229
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21230
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21231
21232
0
    ImGuiListClipper clipper;
21233
0
    clipper.Begin(g.DebugLogIndex.size());
21234
0
    while (clipper.Step())
21235
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21236
0
        {
21237
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
21238
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
21239
0
            TextUnformatted(line_begin, line_end); // Display line
21240
0
            ImRect text_rect = g.LastItemData.Rect;
21241
0
            if (IsItemHovered())
21242
0
                for (const char* p = line_begin; p <= line_end - 10; p++) // Search for 0x???????? identifiers
21243
0
                {
21244
0
                    ImGuiID id = 0;
21245
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21246
0
                        continue;
21247
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
21248
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
21249
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21250
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21251
0
                        DebugLocateItemOnHover(id);
21252
0
                    p += 10;
21253
0
                }
21254
0
        }
21255
0
    g.DebugLogFlags = backup_log_flags;
21256
0
    if (GetScrollY() >= GetScrollMaxY())
21257
0
        SetScrollHereY(1.0f);
21258
0
    EndChild();
21259
21260
0
    End();
21261
0
}
21262
21263
//-----------------------------------------------------------------------------
21264
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21265
//-----------------------------------------------------------------------------
21266
21267
// Draw a small cross at current CursorPos in current window's DrawList
21268
void ImGui::DebugDrawCursorPos(ImU32 col)
21269
0
{
21270
0
    ImGuiContext& g = *GImGui;
21271
0
    ImGuiWindow* window = g.CurrentWindow;
21272
0
    ImVec2 pos = window->DC.CursorPos;
21273
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21274
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21275
0
}
21276
21277
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21278
void ImGui::DebugDrawLineExtents(ImU32 col)
21279
0
{
21280
0
    ImGuiContext& g = *GImGui;
21281
0
    ImGuiWindow* window = g.CurrentWindow;
21282
0
    float curr_x = window->DC.CursorPos.x;
21283
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21284
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21285
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21286
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21287
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21288
0
}
21289
21290
// Draw last item rect in ForegroundDrawList (so it is always visible)
21291
void ImGui::DebugDrawItemRect(ImU32 col)
21292
0
{
21293
0
    ImGuiContext& g = *GImGui;
21294
0
    ImGuiWindow* window = g.CurrentWindow;
21295
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21296
0
}
21297
21298
// [DEBUG] Locate item position/rectangle given an ID.
21299
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21300
21301
void ImGui::DebugLocateItem(ImGuiID target_id)
21302
0
{
21303
0
    ImGuiContext& g = *GImGui;
21304
0
    g.DebugLocateId = target_id;
21305
0
    g.DebugLocateFrames = 2;
21306
0
    g.DebugBreakInLocateId = false;
21307
0
}
21308
21309
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21310
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21311
0
{
21312
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21313
0
        return;
21314
0
    ImGuiContext& g = *GImGui;
21315
0
    DebugLocateItem(target_id);
21316
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21317
21318
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21319
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21320
0
    {
21321
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21322
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21323
0
            g.DebugBreakInLocateId = true;
21324
0
    }
21325
0
}
21326
21327
void ImGui::DebugLocateItemResolveWithLastItem()
21328
0
{
21329
0
    ImGuiContext& g = *GImGui;
21330
21331
    // [DEBUG] Debug break requested by user
21332
0
    if (g.DebugBreakInLocateId)
21333
0
        IM_DEBUG_BREAK();
21334
21335
0
    ImGuiLastItemData item_data = g.LastItemData;
21336
0
    g.DebugLocateId = 0;
21337
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21338
0
    ImRect r = item_data.Rect;
21339
0
    r.Expand(3.0f);
21340
0
    ImVec2 p1 = g.IO.MousePos;
21341
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21342
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21343
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21344
0
}
21345
21346
void ImGui::DebugStartItemPicker()
21347
0
{
21348
0
    ImGuiContext& g = *GImGui;
21349
0
    g.DebugItemPickerActive = true;
21350
0
}
21351
21352
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21353
void ImGui::UpdateDebugToolItemPicker()
21354
22.2k
{
21355
22.2k
    ImGuiContext& g = *GImGui;
21356
22.2k
    g.DebugItemPickerBreakId = 0;
21357
22.2k
    if (!g.DebugItemPickerActive)
21358
22.2k
        return;
21359
21360
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21361
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21362
0
    if (IsKeyPressed(ImGuiKey_Escape))
21363
0
        g.DebugItemPickerActive = false;
21364
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21365
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21366
0
    {
21367
0
        g.DebugItemPickerBreakId = hovered_id;
21368
0
        g.DebugItemPickerActive = false;
21369
0
    }
21370
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21371
0
        if (change_mapping && IsMouseClicked(mouse_button))
21372
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21373
0
    SetNextWindowBgAlpha(0.70f);
21374
0
    if (!BeginTooltip())
21375
0
        return;
21376
0
    Text("HoveredId: 0x%08X", hovered_id);
21377
0
    Text("Press ESC to abort picking.");
21378
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21379
0
    if (change_mapping)
21380
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21381
0
    else
21382
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21383
0
    EndTooltip();
21384
0
}
21385
21386
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21387
void ImGui::UpdateDebugToolStackQueries()
21388
22.2k
{
21389
22.2k
    ImGuiContext& g = *GImGui;
21390
22.2k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21391
21392
    // Clear hook when id stack tool is not visible
21393
22.2k
    g.DebugHookIdInfo = 0;
21394
22.2k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21395
22.2k
        return;
21396
21397
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21398
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21399
2
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21400
2
    if (tool->QueryId != query_id)
21401
0
    {
21402
0
        tool->QueryId = query_id;
21403
0
        tool->StackLevel = -1;
21404
0
        tool->Results.resize(0);
21405
0
    }
21406
2
    if (query_id == 0)
21407
2
        return;
21408
21409
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21410
0
    int stack_level = tool->StackLevel;
21411
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21412
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21413
0
            tool->StackLevel++;
21414
21415
    // Update hook
21416
0
    stack_level = tool->StackLevel;
21417
0
    if (stack_level == -1)
21418
0
        g.DebugHookIdInfo = query_id;
21419
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21420
0
    {
21421
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21422
0
        tool->Results[stack_level].QueryFrameCount++;
21423
0
    }
21424
0
}
21425
21426
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21427
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21428
0
{
21429
0
    ImGuiContext& g = *GImGui;
21430
0
    ImGuiWindow* window = g.CurrentWindow;
21431
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21432
21433
    // Step 0: stack query
21434
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21435
0
    if (tool->StackLevel == -1)
21436
0
    {
21437
0
        tool->StackLevel++;
21438
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21439
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21440
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21441
0
        return;
21442
0
    }
21443
21444
    // Step 1+: query for individual level
21445
0
    IM_ASSERT(tool->StackLevel >= 0);
21446
0
    if (tool->StackLevel != window->IDStack.Size)
21447
0
        return;
21448
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21449
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21450
21451
0
    switch (data_type)
21452
0
    {
21453
0
    case ImGuiDataType_S32:
21454
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21455
0
        break;
21456
0
    case ImGuiDataType_String:
21457
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21458
0
        break;
21459
0
    case ImGuiDataType_Pointer:
21460
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21461
0
        break;
21462
0
    case ImGuiDataType_ID:
21463
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21464
0
            return;
21465
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21466
0
        break;
21467
0
    default:
21468
0
        IM_ASSERT(0);
21469
0
    }
21470
0
    info->QuerySuccess = true;
21471
0
    info->DataType = data_type;
21472
0
}
21473
21474
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21475
0
{
21476
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21477
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21478
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21479
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21480
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21481
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21482
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21483
0
        return (*buf = 0);
21484
#ifdef IMGUI_ENABLE_TEST_ENGINE
21485
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
21486
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21487
#endif
21488
0
    return ImFormatString(buf, buf_size, "???");
21489
0
}
21490
21491
// ID Stack Tool: Display UI
21492
void ImGui::ShowIDStackToolWindow(bool* p_open)
21493
0
{
21494
0
    ImGuiContext& g = *GImGui;
21495
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21496
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
21497
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21498
0
    {
21499
0
        End();
21500
0
        return;
21501
0
    }
21502
21503
    // Display hovered/active status
21504
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21505
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21506
0
    const ImGuiID active_id = g.ActiveId;
21507
#ifdef IMGUI_ENABLE_TEST_ENGINE
21508
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21509
#else
21510
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
21511
0
#endif
21512
0
    SameLine();
21513
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21514
21515
    // CTRL+C to copy path
21516
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21517
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21518
0
    SameLine();
21519
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21520
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, ImGuiInputFlags_RouteGlobal))
21521
0
    {
21522
0
        tool->CopyToClipboardLastTime = (float)g.Time;
21523
0
        char* p = g.TempBuffer.Data;
21524
0
        char* p_end = p + g.TempBuffer.Size;
21525
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21526
0
        {
21527
0
            *p++ = '/';
21528
0
            char level_desc[256];
21529
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21530
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21531
0
            {
21532
0
                if (level_desc[n] == '/')
21533
0
                    *p++ = '\\';
21534
0
                *p++ = level_desc[n];
21535
0
            }
21536
0
        }
21537
0
        *p = '\0';
21538
0
        SetClipboardText(g.TempBuffer.Data);
21539
0
    }
21540
21541
    // Display decorated stack
21542
0
    tool->LastActiveFrame = g.FrameCount;
21543
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21544
0
    {
21545
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
21546
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21547
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21548
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21549
0
        TableHeadersRow();
21550
0
        for (int n = 0; n < tool->Results.Size; n++)
21551
0
        {
21552
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21553
0
            TableNextColumn();
21554
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21555
0
            TableNextColumn();
21556
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21557
0
            TextUnformatted(g.TempBuffer.Data);
21558
0
            TableNextColumn();
21559
0
            Text("0x%08X", info->ID);
21560
0
            if (n == tool->Results.Size - 1)
21561
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21562
0
        }
21563
0
        EndTable();
21564
0
    }
21565
0
    End();
21566
0
}
21567
21568
#else
21569
21570
void ImGui::ShowMetricsWindow(bool*) {}
21571
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21572
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21573
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21574
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21575
void ImGui::DebugNodeFont(ImFont*) {}
21576
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21577
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21578
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21579
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21580
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21581
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21582
21583
void ImGui::DebugLog(const char*, ...) {}
21584
void ImGui::DebugLogV(const char*, va_list) {}
21585
void ImGui::ShowDebugLogWindow(bool*) {}
21586
void ImGui::ShowIDStackToolWindow(bool*) {}
21587
void ImGui::DebugStartItemPicker() {}
21588
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21589
21590
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21591
21592
//-----------------------------------------------------------------------------
21593
21594
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21595
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21596
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21597
#include "imgui_user.inl"
21598
#endif
21599
21600
//-----------------------------------------------------------------------------
21601
21602
#endif // #ifndef IMGUI_DISABLE